Suppose, I want to record say poll choices by users everyday. In this case, i have a table named vote
which has columns poll
, choice
and user-id
. So how can i out the constraint (maybe in the django models or wherever possible) that poll
and user-id
both should not be the same for any entry but like the same user can vote for various different polls once and obviously various users can vote for the same poll. I hope I am clear.
假设,我想记录用户每天的民意调查。在这种情况下,我有一个名为vote的表,其中包含poll,choice和user-id列。那么我怎样才能解决约束(可能在django模型中或在任何可能的情况下),poll和user-id对于任何条目都不应该相同,但是像同一个用户可以投票一次进行各种不同的民意调查,显然各种用户都可以投票对于同一个民意调查。我希望我很清楚。
3 个解决方案
#2
29
The unique_together
attribute of the Meta
class of your model is what you are looking for:
您正在寻找的模型的Meta类的unique_together属性:
class Meta:
unique_together = ('poll', 'user_id')
Check django docs for more information.
查看django文档以获取更多信息。
#3
1
You want the unique_together
attribute: https://docs.djangoproject.com/en/dev/ref/models/options/#unique-together
你想要unique_together属性:https://docs.djangoproject.com/en/dev/ref/models/options/#unique-together
#1
#2
29
The unique_together
attribute of the Meta
class of your model is what you are looking for:
您正在寻找的模型的Meta类的unique_together属性:
class Meta:
unique_together = ('poll', 'user_id')
Check django docs for more information.
查看django文档以获取更多信息。
#3
1
You want the unique_together
attribute: https://docs.djangoproject.com/en/dev/ref/models/options/#unique-together
你想要unique_together属性:https://docs.djangoproject.com/en/dev/ref/models/options/#unique-together