Enes
Enes

Reputation: 341

Django approved comments

first of all, my problem is that I take comments with statusc = 2 and I don't have any problems. But with this code {% for reply in comment.replies.all%} appears with all approved or unanswered replies

views.py

comments=Comment.objects.filter(post=post,reply=None,statusc=2).order_by('-date').....

Model.py

class Comment(models.Model):
STATUS_C_DRAFT = 1
STATUS_C_PUBLISHED = 2
STATUSES_C = (
    (STATUS_C_DRAFT, 'Draft'),
    (STATUS_C_PUBLISHED, 'Published'),
)
post=models.ForeignKey(Post,verbose_name='post',related_name='comment',on_delete=models.CASCADE)
name=models.CharField(verbose_name="name",max_length=60,blank=False)
email=models.EmailField(max_length=120,blank=False,verbose_name="email")
comment=models.TextField(max_length=1000,verbose_name="comment")
reply=models.ForeignKey('Comment',null=True,related_name='replies',on_delete=models.CASCADE)
date=models.DateTimeField(auto_now_add=True)
statusc = models.SmallIntegerField(choices=STATUSES_C,default=STATUS_C_DRAFT)

Html page

 {% for comment in comments %}
                      <!-- POST COMMENT -->
      <div class="post-comment">

        <!-- POST COMMENT USERNAME -->
        <p class="post-comment-username">{{ comment.name }}</p>
        <!-- /POST COMMENT USERNAME -->.... 

        {% for reply in comment.replies.all %}
           <div class="post-comment">

          <!-- POST COMMENT USERNAME -->
          <p class="post-comment-username">{{ reply.name }}</p>
          <!-- /POST COMMENT USERNAME -->...                               
        {% endfor%}
  {%endfor%}

Upvotes: 2

Views: 411

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476594

You can use a Prefetch object here to prefetch the filtered queryset, like:

from django.db.models import Prefetch

comments = Comment.objects.filter(
    post=post, reply=None, statusc=2
).prefetch_related(
    Prefetch('replies', Comment.objects.filter(statusc=2).order_by('-date'), to_attr='approved_replies')
).order_by('-date')

and then you can render this with:

{% for reply in comment.approved_replies.all %}
    <!-- ... -->
{% endfor %}

Note: I would advice to rename your reply field to reply_to, since this looks like more consistent nomenclature.

Upvotes: 3

Related Questions