正确的Django模型关系
前言:我有两个模型(Product
和UserProfile
),我想实现一个评论系统。这个评论是和某个对象相关的,可以是Product
或者UserProfile
。
class Product(models.Model):
name = models.CharField(max_length = 40)
comments = models.ManyToMany(Comment)
class UserProfile(models.Model):
user = models.ForeignKey(User, unique = True)
comments = models.ManyToMany(Comment)
class Comment(models.Model):
text = models.TextField()
author = models.ForeignKey(User)
timestamp = models.DateTimeField(auto_now_add = True)
这样设计逻辑对吗?我有点怀疑,因为这样的话,一个Product
可以有很多评论(这是对的),但同时一个Comment
也可以对应很多产品(我觉得这不太对)。
这样理解对吗?
1 个回答
3
你的评论应该有一个外键,指向用户资料或产品。也就是说,一条评论只能属于一个产品或一个用户资料,但一个用户资料或产品可以有很多不同的评论。
def Comment(models.Model):
profile = models.ForeignKey(UserProfile)
product = models.ForeignKey(Profile)
显然,这样的设计并不理想,因为你需要管理两个关系,有时候你只想用其中一个等等。
为了解决这个问题,你可以使用通用外键:
https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#generic-relations
这样你就可以把评论链接到任何类型的内容(比如产品、用户资料等等),而不需要事先指定具体的模型。
def Comment(models.Model):
...
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')