Reputation: 4533
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.
Upvotes: 41
Views: 25269
Reputation: 5483
Django 2.2 introduced UniqueConstraint
and the note in the official documentation on this topic suggests that unique_together
might be deprecated in future. See deprecation note here.
You can add UniqueConstraint
to the Meta.constraints
option of your model class like so:
class Meta:
constraints = [
models.UniqueConstraint(fields=['poll', 'user_id'], name="user-polled")
]
Upvotes: 41
Reputation: 30133
You want the unique_together
attribute:
https://docs.djangoproject.com/en/dev/ref/models/options/#unique-together
Upvotes: 2
Reputation: 7802
The unique_together
attribute of the Meta
class of your model is what you are looking for:
class Meta:
unique_together = ('poll', 'user_id')
Check django docs for more information.
Upvotes: 48