zubinmehta
zubinmehta

Reputation: 4533

Django - create a unique database constraint for 2 or more fields together

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

Answers (4)

Nitin Nain
Nitin Nain

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

Edward Dale
Edward Dale

Reputation: 30133

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

Upvotes: 2

sebpiq
sebpiq

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

Olivier Verdier
Olivier Verdier

Reputation: 49156

unique_together may be what you are looking for.

Upvotes: 19

Related Questions