【问题标题】:How are 'comments' tied to 'article' in django-comments package?django-comments 包中的“评论”如何与“文章”相关联?
【发布时间】:2021-09-10 09:34:46
【问题描述】:

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

from django_comments.models import Comment

class MyCommentModel(Comment):

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

【问题讨论】:

    标签: django django-models django-queryset django-generic-relations


    【解决方案1】:

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

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

    但是如果你想从Article访问cmets,你可以使用GenericRelation

    from django.contrib.contenttypes.fields import GenericRelation
    
    
    class Article(models.Model):
        ...
        comments = GenericRelation(MyCommentModel)
    
    article = Article.objects.get(id=1)
    article.comments.all()
    

    【讨论】:

      猜你喜欢
      • 2013-02-15
      • 1970-01-01
      • 2012-11-08
      • 1970-01-01
      • 1970-01-01
      • 2021-01-07
      • 1970-01-01
      • 1970-01-01
      • 2017-12-16
      相关资源
      最近更新 更多