如何访问稍后实例化的模型以在 Django 中进行计算?

How can I access a model that is instantiated later for a calculation in Django?

我是 Python/Django 的新手,遇到以下问题。我的模型结构如下:

class Foo:
    name = models.CharField(max_length=10)

class Bar:
    othername = models.CharField(max_length=10)
    othername2 = models.CharField(max_length=10)
    fkey = models.ForeignKey(Foo, on_delete:models.CASCADE)

class FooBaroo:
    FooBarooInt = models.IntegerField()
    Barkey = models.ForeignKey(Bar, on_delete:models.CASCADE)

关系是1个Foo有多个Bars,1个Bar有多个FooBaroos。我想要的是用 Django 创建一个 table,其中我有一个 Bar class 的完整概览。我要显示的内容之一是一个 Bar 的所有 FooBarooInts 的总和。但是,如果我向 Bar 添加一个 属性 来获取所有相关的 FooBaroo 对象(通过 objects.all().filter()),它在大多数情况下最终不会返回任何东西,但不是全部(我觉得很奇怪).

有人知道我应该如何解决这个问题吗?

query = FooBaroo.objects.filter(Barkey={some_id}).all() # List all values
query_sum = FooBaroo.objects.filter(Barkey={some_id})..aggregate(Sum('Barkey')) # Query to sum

利用related_name and aggregation:

from django.db.models import Sum
class Bar:
    @property 
    def fb_int_sum(self):
        return self.foobaroo_set.aggregate(s=Sum('FooBarooInt')).get('s') or 0
        # return FooBaroo.objects.filter(Barkey=self).agg...

我想你可以用这个:

obj.foobaroo_set.values_list('FooBarooInts')

上面的"obj"是一个你想要求和的自定义Bar,它是FooBarooInts。 请注意 foobaroo_set 必须是小写字母(甚至您的型号名称也不是)。

您可以查看更多详情here and here