2013-08-22 90 views
1

我试图做一个自定义的评论引擎,但我想不出如何显示嵌套的评论。我使用'回复'ForeignKey来跟踪它引用的评论。我正在使用关卡字段来查看它是什么“级别”评论。如何在Django样式模板中收集子注释?

models.py:

class Post(models.Model) 
    name  = models.CharField() 
    text  = models.TextFiled() 

class Comment(models.Model) 
    o_post = models.ForeignKey(Post) 
    reply = models.ForeignKey('self', blank=True, null=True) 
    level = models.IntegerField(default=1) 
    #others like content,author, created etc... 

views.py

def PostComments(request,postpk): 
    post  = Post.objects.get(pk=postpk) 
    comments = Comment.objects.filter(o_post=post).order_by('-created') 
    children = Comment.objects.filter(o_post=post).filter(level__gte=2) 
    context = {'comments':comments,'post':post,'children':children} 
    return render_response(stuff) 

这里是我如何努力,以显示一切。所有1级评论都可见。 child.reply返回一个ID,所以没有comment.pk,它们都匹配41

{% for comment in comments %} 
    {{comment.content}} 
    {% for child in children %} 
     {%if child.reply == comment.pk %} 
      {{child.content}} 
     {% endif %} 
    {% endfor %} 
{% endfor %} 

无论我如何结构的,如果循环我无法弄清楚如何得到它的工作。由于

回答

1

尝试比较实体,不pk

{% if child.reply == comment %} 
+0

什么!工作!但是不应该41 41的答案也通过? – theptrk

+0

我相信你会比较和回复实例41号码 – mikes000

+0

打印像{{child.reply}}这样的实体可能会因为__str __()或__repr __()而显示“41”显示。这并不意味着实体只是一个数字。你也可以使用'{%if child.reply.id == comment.pk%}'。 –