Python Django模板过滤器查询集
我刚到django。 我有一个django应用程序,其中存储按“X”和“Y”分类的产品 views.pyPython Django模板过滤器查询集,python,django,django-templates,django-queryset,Python,Django,Django Templates,Django Queryset,我刚到django。 我有一个django应用程序,其中存储按“X”和“Y”分类的产品 views.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') | Produc
...
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
...
在my views.py中,我根据您的类别slug筛选此产品
问题是,我试图在页面顶部呈现类别“X”中的产品,在类别“Y”中的产品之间呈现文本。我怎么能做到
list.html
{% for category in product_list %}
{{ category.name }}
{% endfor %}
<p>
Any text
</p>
{% for category in product_list %}
{{ category.name }}
{% endfor %}
{%用于产品列表中的类别%}
{{category.name}
{%endfor%}
任何文本
{产品列表%中类别的百分比}
{{category.name}
{%endfor%}
首先,在填充过滤后的查询集时,应使用运算符over
:
def get_queryset(self):
return Product.objects.filter(category__slug__in=["X", "Y"])
其次,您不能按模板中的任何字段过滤queryset,除非您编写了这样做的字段。然而,它破坏了表示代码与数据逻辑分离的目的。过滤模型是数据逻辑,输出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 %}
我没有看到更新。这是工作,谢谢,帮了大忙。