Python Django ORM对象计数

Python Django ORM对象计数,python,django,django-orm,Python,Django,Django Orm,考虑这些伪模型: class BaseProduct: quantity_available = Integer class Box(BaseProduct): items_in_box = Integer >> BaseProduct.objects.count() >> Integer 但是如何检索产品的总数,因此: for each object[quantity_available * items_in_box] * total_objects

考虑这些伪模型:

class BaseProduct:
   quantity_available = Integer

class Box(BaseProduct):
   items_in_box = Integer

>> BaseProduct.objects.count()
>> Integer
但是如何检索产品的总数,因此:

for each object[quantity_available * items_in_box] * total_objects
解决方案: 我使用Simeon Visser的“sum”作为部分解决方案,在基类中添加了一个属性:

@property
def _box_count(self):
    try:
        return self.items_in_box * self.quantity_available
    except AttributeError:
        return self.quantity_available

sum([item._box_count for item in BaseProduct.objects.all()])
请尝试以下操作:

sum([box.quantity_available * box.items_in_box for box in Box.objects.all()]

它检索所有框,并为每个框计算该框的可用数量乘以该类型框中的项目数。最后,它对所有这些值求和,从而得到产品的总数。

我不明白。您是在寻找箱子的总数,还是物品的总数?以及
box
中的项目与
quantity\u available
是如何关联的?您如何管理从
BaseProduct
到数据库中
box
的继承?您是否使用文档中概述的方法之一?BaseProduct有一个quantity\u可用字段(整数)。长方体是从BaseProduct继承而来的,长方体也可以容纳X个产品。比如说你们出售雨伞,每件每盒。我想要雨伞的总库存。我没有定义一个自定义为“叶子”类,比如说,你有什么?Umbrella(BaseProduct)和BoxOfumbrella(BaseProduct)或其他什么?这似乎是一种实用的方法,不过我选择了模型的属性,谢谢