Django template filter queryset

点点圈 提交于 2019-12-11 02:55:41

问题


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
...

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

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

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

<p> 
    Any text 
</p>

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

回答1:


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"])

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 %}


来源:https://stackoverflow.com/questions/43107377/django-template-filter-queryset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!