首先,我的问题是我以statusc = 2进行评论,但没有任何问题。但是使用此代码{% for reply in comment.replies.all%}
会显示所有已批准或未答复的回复
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页面
{% 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%}
答案 0 :(得分:3)
您可以在此处使用Prefetch
对象来预取过滤后的查询集,例如:
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')
,然后您可以使用以下命令呈现此
:{% for reply in comment.approved_replies.all %}
<!-- ... -->
{% endfor %}
注意:我建议您将
reply
字段重命名为reply_to
,因为这看起来更统一。