1

在 Django 自己的评论框架django-contrib-comments中,如果我创建自己的评论模型如下:

from django_comments.models import Comment

class MyCommentModel(Comment):

问:我应该如何将这个新的评论模型 ( MyCommentModel) 与现有Article模型相关联?使用属性content_typeobject_pkcontent_object

4

1 回答 1

1

您可以像这样直接使用它:

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()
于 2021-09-10T11:54:56.713 回答