在Django自己的注释框架中,Django -contrib-comments,如果我创建自己的注释模型,如下所示:
from django_comments.models import Comment
class MyCommentModel(Comment):
Q:我应该如何将这个新的评论模型(MyCommentModel
)与现有的Article
模型关联起来?使用属性content_type
,object_pk
或content_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()