Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django composite unique on multiple model fields

Let us say I have a model for social network posts, users and likes:

class Post(models.Model):
    submitter = models.ForeignKey(User, null=False, default=None)
    content = models.CharField()
    date = models.DateField()

    with_likes = PostLikeCountManager()
    objects = models.Manager()

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

It would be helpful to think of Post model as representing a Facebook post. Now, I would like to limit one like per post per user. How do I achieve that? One way would be to create a composite primary key on (user, post) attributes of Like class. I don't know how to achieve that in Django. The other would be to use unique=True on two attributes simultaneously. Is that possible?

Thanks.

like image 520
abhinavkulkarni Avatar asked Apr 05 '15 20:04

abhinavkulkarni


1 Answers

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')
like image 94
knbk Avatar answered Sep 24 '22 10:09

knbk