Django Threaded Commenting System

Posted by Yasin Ozel on Stack Overflow See other posts from Stack Overflow or by Yasin Ozel
Published on 2014-07-21T07:48:09Z Indexed on 2014/08/18 16:24 UTC
Read the original article Hit count: 307

(and sorry for my english)

I am learning Python and Django. Now, my challange is developing threaded generic comment system. There is two models, Post and Comment.

-Post can be commented.

-Comment can be commented. (endless/threaded)

-Should not be a n+1 query problem in system. (No matter how many comments, should not increase the number of queries)

My current models are like this:

class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()

    child = generic.GenericRelation(
        'Comment',
        content_type_field='parent_content_type',
        object_id_field='parent_object_id'
    )

class Comment(models.Model):
    content = models.TextField()

    child = generic.GenericRelation(
        'self',
        content_type_field='parent_content_type',
        object_id_field='parent_object_id'
    )

    parent_content_type = models.ForeignKey(ContentType)
    parent_object_id = models.PositiveIntegerField()
    parent = generic.GenericForeignKey(
        "parent_content_type", "parent_object_id")

Are my models right? And how can i get all comment (with hierarchy) of post, without n+1 query problem?

Note: I know mttp and other modules but I want to learn this system.


Edit: I run "Post.objects.all().prefetch_related("child").get(pk=1)" command and this gave me post and its child comment. But when I wanna get child command of child command a new query is running. I can change command to ...prefetch_related("child__child__child...")... then still a new query running for every depth of child-parent relationship. Is there anyone who has idea about resolve this problem?

© Stack Overflow or respective owner

Related posts about python

Related posts about django