41

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.

1

4 Answers 4

48

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.

Sign up to request clarification or add additional context in comments.

2 Comments

You'll need a comma between the two close parentheses I think unique_together = (('poll', 'user_id'),).
41

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

Older Django versions (eg. 2.0.6) are not supported, I think. Or is there a work around?
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-versions
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 model
19

unique_together may be what you are looking for.

Comments

2

You want the unique_together attribute: https://docs.djangoproject.com/en/dev/ref/models/options/#unique-together

2 Comments

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.
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.