Skip to main content
 首页 » 编程设计

python之正确的 Django 模型关系

2024年09月03日35over140

前言:我有两个模型(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 可以有很多产品(我认为这是不正确的).

不是吗?

请您参考如下方法:

您的评论应该有一个指向 UserProfile 或 Product 的外键,即单个评论只能属于一个产品或用户个人资料,但用户个人资料/产品可以有许多不同的评论

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')