View .py
def f_page(request, slug, f_slug):
f = get_object_or_404(F, slug= f_slug)
if f:
events = f.event_set.order_by('-pub_date')
if events:
for event in events:
comments = event.comment_set.order_by('-pub_date')
variables = RequestContext(request, {
'f' : f,
'events' : events,
'comments' : comments,
})
return render_to_response('f_page.html', variables)
这里的事件和评论是可迭代的。每个f有多个事件,然后每个事件有多个注释。问题是我如何在我的 html 页面中呈现它。我已经尝试过这个,但它不起作用:
{% for event in events %}
<a href="/{{ event.author.username }}/">{{ event.author.first_name }}</a>
{{ event.pub_date }}
{{ event.description }}
{% for comment in comments %}
{{ comment }}
{{ comment.author.first_name }}
{% endfor %}
{% endfor %}
事件部分显示正确,但评论集不显示。 我的模型工作得很好,我已经尝试了管理面板中的所有内容。我可以看到哪里搞砸了,但无法解决。在“views.py”中,每个事件的评论对象都没有被保存。但是,我不知道如何解决。 请帮忙。提前致谢。
最佳答案
您可以在模板中获取它,而不是将注释
传递给模板。
{% for event in events %}
<a href="/{{ event.author.username }}/">{{ event.author.first_name }}</a>
{{ event.pub_date }}
{{ event.description }}
{% for comment in event.comment_set.all %}
{{ comment }}
{{ comment.author.first_name }}
{% endfor %}
{% endfor %}
添加ordering
模型 Meta
类中的字段,以便 event.comment_set.all
为您提供订单中的数据。
class Comment(Model):
...
class Meta:
ordering = ['-pub_date']
关于python - 在 Django 的 html 页面中渲染多个查询集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20086993/