Unique Django Composition for Multiple Model Fields

Let's say I have a model for social media posts, users like it:

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 recall the Post model as representing the Facebook post. Now I would like to limit one thing per message per user. How do I achieve this? One way is to create a composite primary key ( user , Post ) of the attributes of the Like class. I do not know how to achieve this in Django. Another is to use unique=True for two attributes at the same time. Is it possible?

Thanks.

+12
source share
1 answer

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') 
+18
source

Source: https://habr.com/ru/post/984714/


All Articles