django-comments包中自定义评论模型如何与Article模型关联?
关联方案说明
django-contrib-comments自带的Comment基类通过通用外键实现和任意业务模型的关联,三个属性的用法区别如下:
- 优先使用
content_object属性:这是最简便的写法,直接传入要关联的Article实例即可,Django会自动解析填充对应的content_type和object_pk字段,无需手动处理。
示例代码:target_article = Article.objects.get(id=要关联的文章ID) new_comment = MyCommentModel( content_object=target_article, comment="评论内容", # 其他必填字段按需求补充 ) new_comment.save() - 如有特殊场景需要手动赋值(比如批量插入、避免额外查询ContentType表),可以同时给
content_type和object_pk赋值,两者缺一不可:
示例代码:from django.contrib.contenttypes.models import ContentType article_content_type = ContentType.objects.get_for_model(Article) new_comment = MyCommentModel( content_type=article_content_type, object_pk=要关联的文章ID, comment="评论内容", # 其他必填字段按需求补充 ) new_comment.save()
如果需要在Article侧反向查询所有关联的自定义评论,可以在Article模型中添加GenericRelation字段:
from django.contrib.contenttypes.fields import GenericRelation class Article(models.Model): # 原有字段保持不变 comments = GenericRelation(MyCommentModel)
配置后可直接通过article_instance.comments.all()获取该文章下的所有自定义评论。
内容的提问来源于stack exchange,提问作者Yan Tian
相关产品推荐
相关产品推荐

