简体   繁体   English

如何在Django中获得3级对象计数

[英]How to get 3rd level Object count in Django

I'm building a list of sections, categories and subcategories for a small e-market project on Django. 我正在为Django上的一个小型电子市场项目构建部分,类别和子类别的列表。

I have a model like this: 我有一个这样的模型:

Section > Category (FK Section) > SubCategory (FK Category) > ShopProduct (FK SubCategory) 部分>类别(FK类别)>子类别(FK类别)> ShopProduct(FK子类别)

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. 如果分配给该部分的类别超过1个,它将过滤这些部分。 (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. 因此,您需要从ShopProduct开始并遵循这些关系。 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 }} . 因此,您需要将其定义为Section类的一种方法,用self代替my_section ,然后可以执行(例如) {{ section.get_product_count }}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM