Django模板过滤器queryset [英] Django template filter queryset

查看:144
本文介绍了Django模板过滤器queryset的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是django的新朋友。
我有一个django应用程序,其中存储了按 X和 Y分类的产品。

I'm new in django. I has a django application where stores products categorized by 'X' and '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') | 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中,我会根据您的类别过滤此产品。

In my views.py I filter this products by your categories slug.

问题是,我正在尝试在页面顶部呈现 X类别中的产品,而将 Y类别中的产品向下呈现文本。我该怎么做?

The problem is, I'm trying to render the products in category 'X' on top the page and the products in category 'Y' down with a text between them. How I can do this?

list.html

list.html

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

<p> 
    Any text 
</p>

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


推荐答案

首先,您应该使用 IN 运算符,超过 | 填充过滤的查询集时:

First off, you should use IN operator over | when populating the filtered queryset:

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

第二,您不能按以下任何字段过滤查询集除非您编写自定义模板标签那。但是,它无法实现将表示代码与数据逻辑分离的目的。过滤模型是数据逻辑,而输出HTML是表示。因此,您需要覆盖 get_context_data 并将每个查询集传递到上下文中:

Secondly, you can't filter queryset by any field in the template unless you write a custom template tag which does that. However, it defeats the purpose of separation of presentation code from data logic. Filtering models is data logic, and outputting HTML is presentation. Thus, you need to override get_context_data and pass each queryset into the context:

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

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

Then you can use them in the template:

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

...

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

这篇关于Django模板过滤器queryset的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆