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

19👍

unique_together may be what you are looking for.

47👍

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.

👤sebpiq

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

2👍

Leave a comment