我试图打印出4个条目。它工作,只要我没有任何条目没有发布。
如何获取仅包含“已发布”管理器中对象的查询集?
现在我使用:{%if benefit.status ==“p”%}不打印那些未发布的条目,但是未发布的影响切片计数。
#views.py:
class PackageListFrontpage(ListView):
context_object_name = "package_frontpage_list"
template_name = "frontpage.html"
queryset = Package.published.all().order_by('order')[:5]
#frontpage.html
{% for package in package_frontpage_list %}
<div>
<h3>{{ package.name }} >></h3>
<ul>
{% for benefit in package.benefit_set.all|slice:":4" %}
{% if benefit.status == "p" %}
<li><a href="{{ benefit.get_absolute_url }}">{{ benefit.name }}</a></li>
{% endif %}
{% empty %}
<li>There are no published benefits in this package</li>
{% endfor %}
</ul>
</div>
{% endfor %}
我想有更好的方法吗?
答案 0 :(得分:0)
您可以在Package
模型上定义一个方法,该方法返回已发布的相关权益的查询集。
class Package(object):
...
def benefit_set_published(self):
"""
Return the related benefits which are published
"""
return self.benefit_set.filter(status="p")
然后将模板更改为:
{% for benefit in package.benefit_set_published.all|slice:":4" %}
<li><a href="{{ benefit.get_absolute_url }}">{{ benefit.name }}</a></li>
{% empty %}
<li>There are no published benefits in this package</li>
{% endfor %}