我是 Django 新手。 我有一个 Django 应用程序,其中存储按“X”和“Y”分类的产品。
View .py
...
class CartListView(ListView):
template_name = 'checkout/list.html'
context_object_name = 'product_list'
def get_queryset(self):
return Product.objects.filter(category__slug='X') | Product.objects.filter(category__slug='Y')
def get_context_data(self, **kwargs):
context = super(CartListView, self).get_context_data(**kwargs)
context['minicurso'] = get_object_or_404(Category, slug='X')
context['pacotes'] = get_object_or_404(Category, slug='Y')
return context
...
在我的views.py中,我按您的类别slug过滤此产品。
问题是,我试图在页面顶部呈现类别“X”中的产品,在页面顶部呈现类别“Y”中的产品,并在它们之间显示文本。我怎样才能做到这一点?
列表.html
{% for category in product_list %}
{{ category.name }}
{% endfor %}
<p>
Any text
</p>
{% for category in product_list %}
{{ category.name }}
{% endfor %}
最佳答案
首先,您应该使用 IN
填充过滤后的查询集时,对 |
进行运算符:
def get_queryset(self):
return Product.objects.filter(category__slug__in=["X", "Y"])
其次,你不能通过模板中的任何字段过滤查询集,除非你写 a custom template tag这样做的。然而,它违背了表示代码与数据逻辑分离的目的。过滤模型是数据逻辑,输出HTML是呈现。因此,您需要重写 get_context_data
并将每个查询集传递到上下文中:
def get_context_data(self, **kwargs):
context = super(CartListView, self).get_context_data(**kwargs)
context['minicurso'] = get_object_or_404(Category, slug='X')
context['pacotes'] = get_object_or_404(Category, slug='Y')
context["x_product_list"] = self.get_queryset().filter(category=context['minicurso'])
context["y_product_list"] = self.get_queryset().filter(category=context['pacotes'])
return context
然后您可以在模板中使用它们:
{% for category in x_product_list %}
{{ category.name }}
{% endfor %}
...
{% for category in y_product_list %}
{{ category.name }}
{% endfor %}
关于python - Django 模板过滤器查询集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43107377/