【问题标题】:Django template filter querysetDjango 模板过滤器查询集
【发布时间】:2023-04-11 06:53:01
【问题描述】:

我是 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') | 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 中,我按您的分类筛选了这个产品。

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

list.html

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

<p> 
    Any text 
</p>

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

【问题讨论】:

    标签: python django django-templates django-queryset


    【解决方案1】:

    首先,在填充过滤后的查询集时,您应该使用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 %}
    

    【讨论】:

    • 我没有看到更新。这是工作,谢谢,帮助很大。
    猜你喜欢
    • 1970-01-01
    • 2018-09-02
    • 2021-04-21
    • 2019-07-29
    • 1970-01-01
    • 2014-06-12
    • 2020-09-10
    • 2020-08-22
    • 2019-04-15
    相关资源
    最近更新 更多