Django复合在多个模型字段上是唯一的 [英] Django composite unique on multiple model fields
本文介绍了Django复合在多个模型字段上是唯一的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
让我们说我有一个社交网络帖子,用户和喜欢的模型:
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)
将 Post
模型视为代表 Facebook
帖子是很有帮助的.现在,我想限制每个用户每条帖子的赞数.我该如何实现?一种方法是在 Like
类的( user
, post
)属性上创建一个复合主键.我不知道如何在Django中实现这一目标.另一种方法是同时对两个属性使用 unique = 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?
谢谢.
推荐答案
是的,请使用唯一在一起:
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')
这篇关于Django复合在多个模型字段上是唯一的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文