django-如何仅允许使用独立的数量重复数量?
我正在制作一个网页 - 一个可以租用电影,音乐CD和书籍的租赁场所。 我已经创建了一个CD模型 -
class Cd(models.Model):
cd_band=models.CharField(max_length=100)
cd_title=models.CharField(max_length=100)
CD_GENRE= (
('POP', "POP"),
("HIP", "Hip-Hop"),
("ROC", "Rock"),
("BLU", "Blues"),
("SOU", "Soul"),
("COU", "Country"),
("JAZ", "Jazz"),
("CLA", "Classical music"),
)
cd_genre=models.CharField(max_length=3, choices=CD_GENRE)
cd_length=models.DurationField()
cd_rental=models.ForeignKey(Rental, on_delete=models.CASCADE, default=1)
def __str__(self):
# return self.cd_title, '\n', self.cd_band, '\n'
return "{} {} {}".format(self.cd_band,self.cd_title,self.cd_genre)
但是我必须在这里应用一条规则:
- 一个乐队可以在多达2种流派中提供CD。因此,假设我创建了Band1 -band1的CD,只能在2种流派中使用CD -Fe Rock and Blues。我不知道如何实施。 我正在考虑制定一个约束,但我不知道要实现哪种条件:
UniqueConstraint.condition(fields=['cd_band','cd_genre'],condition=??????, name='unique_cd')
我还考虑过重组整个数据库 - 为乐队和音乐流派组成单独的类,然后将其与外国钥匙链接,设置向上验证器。我认为它应该可以工作,但是我必须做很多工作。 还有其他方法吗?
I'm making a webpage - a rental place that can rent movies, music cd's and books.
I've created a model of cd -
class Cd(models.Model):
cd_band=models.CharField(max_length=100)
cd_title=models.CharField(max_length=100)
CD_GENRE= (
('POP', "POP"),
("HIP", "Hip-Hop"),
("ROC", "Rock"),
("BLU", "Blues"),
("SOU", "Soul"),
("COU", "Country"),
("JAZ", "Jazz"),
("CLA", "Classical music"),
)
cd_genre=models.CharField(max_length=3, choices=CD_GENRE)
cd_length=models.DurationField()
cd_rental=models.ForeignKey(Rental, on_delete=models.CASCADE, default=1)
def __str__(self):
# return self.cd_title, '\n', self.cd_band, '\n'
return "{} {} {}".format(self.cd_band,self.cd_title,self.cd_genre)
But there is a rule that I have to apply here:
-One band can offer cd's in up to 2 genres. So let's say I create a cd of Band1 - Band1 can have cd's in only 2 genres - f.e rock and blues. I have no idea how to implement that.
I'm thinking about making a constraint, but I don't know what condition to implement:
UniqueConstraint.condition(fields=['cd_band','cd_genre'],condition=??????, name='unique_cd')
I've also thought of restructurizing my entire database - making a separate classes for bands and music genres, and then linking it with foreign keys, setting up validators. I think it should work, but I'd have to put in so much work.
Is there any other way of doing it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您想以这种方式构造数据库,那么IMO并不适合操纵和未来功能。我将支票放入
save()
方法中。类似的内容:*编辑:忘记添加通常您要在
.distinct()
valice_list()之后使用.distinct()
,但是当我选择使用set时( )
此解决方案。它不需要,并且具有与Difinse()
相同的效果。If you want to have the database structured this way, which is IMO not great for manipulation and future features. I'd put the check into
save()
method. Something like this:*Edit: Forgot to add that usually you want to use
.distinct()
aftervalues_list()
, but as I chose to useset()
for this solution. It is not needed and has the same effect asdistinct()
.