在 django-comments 包中,"评论"如何与"文章"相关联?



在Django自己的注释框架中,Django -contrib-comments,如果我创建自己的注释模型,如下所示:

from django_comments.models import Comment
class MyCommentModel(Comment):

Q:我应该如何将这个新的评论模型(MyCommentModel)与现有的Article模型关联起来?使用属性content_type,object_pkcontent_object?

你可以直接这样使用:

article = Article.objects.get(id=1)
comment = MyCommentModel(content_object=article, comment='my comment')
comment.save()

但是如果你想访问Article的注释,你可以使用GenericRelation:

from django.contrib.contenttypes.fields import GenericRelation

class Article(models.Model):
...
comments = GenericRelation(MyCommentModel)
article = Article.objects.get(id=1)
article.comments.all()

最新更新