I'm building a list of sections, categories and subcategories for a small e-market project on Django.
I have a model like this:
Section > Category (FK Section) > SubCategory (FK Category) > ShopProduct (FK SubCategory)
The problem is that I have many of categories (and subcategories) which are empty, and for that reason I filter data in the query set with:
{% if section.shopcategory_set.count > 0 %}
It will filter the sections if there are more than 1 categories assigned to this section. (But it doesn't filter if any items are assigned deeper)
So, I want to count final objects from the first level cycle
Something like:
{% for section in sections %}
{% if section.category_set.subcategory_set.shopproduct_set.count > 0 %}
{{ section.name }}
{% endif %}
{% endfor %}
The general principle is to start from the object you want to retrieve, or in this case count. So, you need to start with ShopProduct and follow the relationships. In a view that would be:
ShopProduct.objects.filter(subcategory__category__section=my_section)
However, you can't do this in the template, because you can't call methods with parameters. So you'd need to define this as a method on the Section class, replacing my_section
with self
, then you can do (eg) {{ section.get_product_count }}
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.