Search code examples
djangodjango-modelsdjango-querysetdjango-generic-relations

How are 'comments' tied to 'article' in django-comments package?


In Django's own comment framework, django-contrib-comments, if I create my own comment model as below:

from django_comments.models import Comment

class MyCommentModel(Comment):

Q: How should I associate this new comment model (MyCommentModel) with existing Article model? using attribute content_type, object_pk or content_object ?


Solution

  • You can just use it directly like this:

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

    But if you want to access the comments from Article, you can use GenericRelation:

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