Django模板筛选器查询

2024-10-01 09:36:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我是django的新人。 我有一个django应用程序,其中存储按“X”和“Y”分类的产品。在

在视图.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
...

在我的视图.py我按你的类别过滤这些产品。在

问题是,我试图在页面顶部呈现“X”类别的产品,在页面顶部呈现“Y”类别中的产品,并在它们之间添加文本。我该怎么做?在

在列表.html在

^{pr2}$

Tags: djangonamepyself视图getobject产品
1条回答
网友
1楼 · 发布于 2024-10-01 09:36:54

首先,在填充筛选的查询集时,应该在|上使用^{}运算符:

def get_queryset(self):
    return Product.objects.filter(category__slug__in=["X", "Y"])

其次,您不能通过模板中的任何字段过滤queryset,除非您编写了a custom template tag这样做。然而,它违背了将表示代码与数据逻辑分离的目的。过滤模型是数据逻辑,输出HTML是表示。因此,您需要重写get_context_data,并将每个查询集传递到上下文中:

^{pr2}$

然后可以在模板中使用它们:

{% for category in x_product_list %}
  {{ category.name }}
{% endfor %}

...

{% for category in y_product_list %}
  {{ category.name }}
{% endfor %}

相关问题 更多 >