前言:我有两个模型(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
也可以有很多产品(我认为这是不正确的) )。
不是吗?
最佳答案
您的评论应该具有用户个人资料或产品的外键,即单个评论只能属于单个产品或用户个人资料,但用户个人资料/产品可以有许多不同的评论
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')
关于python - 正确的 Django 模型关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6717135/