显示对Django中个人评论的回复

时间:2015-01-07 05:35:43

标签: python django

我正在构建评论系统,我想显示对评论的回复。

Models:
class Comment(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    thread = models.ForeignKey(Thread)
    body = models.TextField(max_length=10000)
    slug = models.SlugField(max_length=40, unique=True)

class Reply(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    post = models.ForeignKey(Post)
    body = models.TextField(max_length=1000)

问题是我真的不知道如何将与个别评论相关的回复发送到模板。目前,我的观点是:

Views
def view_thread(request, thread_slug):
    thread = Thread.objects.get(slug=thread_slug)
    comments = Comment.objects.filter(thread = thread)
    if request.method == 'POST':
        form = ResponderForm(request.POST)
        if form.is_valid():
            comment = Comment()
            comment.body = form.cleaned_data['body']
            comment.thread = thread
            comment.save()
            new_form = ResponderForm()
            reply_form = ReplyForm()
            return render(request, 'view_thread.html', {
                                      'Thread': thread,
                                      'form': new_form,
                                      'replyform': reply_form,
                                      'Comments': comments.order_by('-created'),
            })
    else:
        form = ResponderForm()
        thread = Thread.objects.get(slug=thread_slug)
        reply_form = ReplyForm()
        return render(request, 'view_thread.html', {
                                  'Thread': thread,
                                  'form': form,
                                  'replyform': reply_form,
                                  'Comments': comments.order_by('-created'),
        })

它工作正常,我可以看到线程和它的评论。但是,我应该如何继续执行以下操作以显示对每条评论的回复?

{% for Comment in comments %}
 {{ Comment.body }}
 {%for Reply in replies %}
  {{Reply.body }}
 {% endfor %}
{% endfor %}

我尝试了一些可怕的解决方法,但是没有用。我知道有一些软件包可以做到这一点但是因为我还在学习,所以我认为自己做这件事会更好。此外,我之前已经意识到这个问题,但回复没有澄清我的问题。

似乎我在这里缺少一些基本的东西。 谢谢。

1 个答案:

答案 0 :(得分:0)

"向后"关系是described in the docs

{% for Reply in Comment.reply_set.all %}
    {{ Reply.body }}
{% endfor %}