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.
- possible duplicate of How to define two fields "unique" as coupleeducampver– educampver2013-10-26 04:01:28 +00:00Commented Oct 26, 2013 at 4:01
Add a comment |
4 Answers
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.
2 Comments
Dominic Rodger
You'll need a comma between the two close parentheses I think
unique_together = (('poll', 'user_id'),).dialex
Actually it's not needed: docs.djangoproject.com/en/dev/ref/models/options/…
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") ] 3 Comments
Stop War
Older Django versions (eg. 2.0.6) are not supported, I think. Or is there a work around?
Nitin Nain
There's
unique_together as suggested in the other answers. Django 2.0 is out of support btw, if you can update it do that! djangoproject.com/download/#supported-versionsRobert Johnstone
Why is the usage of
uniqueTogether not shown in the documentation? I had to come here to find I have to have it in a list called constraints, in the Meta class of the modelYou want the unique_together attribute: https://docs.djangoproject.com/en/dev/ref/models/options/#unique-together
2 Comments
Edward Dale
As far as I know, you can suggest an edit to this answer if it doesn't please you in some way. That will then be accepted, assuming your suggested edit isn't crap, and you will have contributed something positive to the world. Downvoting an answer that's 3 years old when the accepted answer is still correct seems a bit unnecessary, but I guess it's your prerogative.
Drachenfels
You have to agree that answer that is just one sentence with link and this link is broken is not a really good answer, is it? :) Contrary there is upvoted one that is acceptect and link is correct. That's why one I value other I don't.