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

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


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.


unique_together may be what you are looking for.


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")
        ]