【问题标题】:Render multiple quersets in html page in Django在 Django 的 html 页面中呈现多个查询集
【发布时间】:2023-04-09 22:16:01
【问题描述】:

views.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)

这里的事件和 cmets 是可迭代的。每个 f 有多个事件,然后每个事件有多个 cmet。问题是如何在我的 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”中,每个事件的 cmets 对象都没有被保存。但是,我不知道如何解决它。 请帮忙。提前致谢。

【问题讨论】:

    标签: python html django views django-queryset


    【解决方案1】:

    您可以在模板中获取它,而不是将comments 传递给模板。

    {% 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 %} 
    

    在您的模型Meta 类中添加ordering 字段,以便event.comment_set.all 为您提供按顺序排列的数据。

    class Comment(Model):
       ...
       class Meta:
            ordering = ['-pub_date']
    

    【讨论】:

    • 谢谢!它工作正常。在模板中进行查询是否有任何性能问题?
    • @Monica,不要认为存在性能问题。此外,您的代码的一个问题是您想要每个事件的comments 列表,但您只存储一个(最后一个)。
    猜你喜欢
    • 2013-12-03
    • 1970-01-01
    • 1970-01-01
    • 2013-07-01
    • 1970-01-01
    • 2018-05-09
    • 2017-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多