[Django]-Django composite unique on multiple model fields

33👍

Yes, use unique_together:

class Like(models.Model):
    user = models.ForeignKey(User)
    post = models.ForeignKey(Post)
    time = models.DateTimeField(auto_now_add=True)

    class Meta:
        unique_together = ('user', 'post')
👤knbk

20👍

unique_together will be deprecated in the future version, instead you could apply UniqueConstraint. This and this link gives example code.

class Like(models.Model):
    user = models.ForeignKey(User)
    post = models.ForeignKey(Post)
    time = models.DateTimeField(auto_now_add=True)

    class Meta:
        constraints = [
            models.UniqueConstraint(fields=['user', 'post'], name='unique_user_post'),
        ]
👤Ham

Leave a comment