首页 > 解决方案 > 在 django/python 我的主页中仅列出三个元素

问题描述

{% for post in BusinessPost %}
<ul>
    <li>{{ post.title}} -- {{post.author}} -- {{post.source_date}} </li>
</ul>
{% endfor %}

这是我将模型的所有元素放入 listView 页面的代码,但我只想获取此列表的前 3 个元素。谁能帮忙

标签: pythondjangodjango-templates

解决方案


您可以使用以下方法对查询集进行切片:

class BusinessPostListView(ListView):
    #                  obtain the first 3 ↓
    queryset = BusinessPost.objects.all()[:3]

    # …

推荐阅读