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

标签 python django models

我对 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有多个Bar,1个Bar有多个FooBaroo。我想要的是用 Django 创建一个表,其中我对 Bar 类有完整的概述。我想要显示的内容之一是 Bar 的所有 FooBarooInts 的总和。然而,如果我向 Bar 添加一个属性来获取所有相关的 FooBaroo 对象(通过objects.all().filter()),它最终在大多数情况下不会返回任何内容,但不是全部(我觉得这很奇怪)。

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

最佳答案

利用related_nameaggregation :

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

关于python - 如何访问稍后实例化的模型以在 Django 中进行计算?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46825512/

相关文章:

python - 无法在 Django Model 中调用 save() ?获取: AttributeError: 'unicode' object has no attribute 'save'

python - Select_Analysis 工具上的循环(Python 和 ArcGIS 9.3)

python - Scipy:如何将 KD-Tree 距离从查询转换为千米(Python/Pandas)

python - 如何在reactjs中使用jwt token 发送axios put请求

python - dynamodb boto put_item 类型为 Map "M"

python - 在 Django 中使用抽象多重继承时外键冲突

php - 模型和模型资源之间的区别

python - __repr__ 用于(大型)复合对象

Python 方法访问器在每次访问时创建新对象?

django - 检查选定的多对多关系字段是否不相交