开发者

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 a开发者_如何学Gond obviously various users can vote for the same poll. I hope I am clear.


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.


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


unique_together may be what you are looking for.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜