Django:如何在聚合中使用外键字段?

时间:2021-09-09 19:34:33

Let's say I have the following two models:

假设我有以下两种型号:

class Parent(models.Model):
    factor = models.DecimalField(...)
    ... other fields

class Child(models.Model):
    field_a = models.DecimalField(...)
    field_b = models.DecimalField(...)
    parent = models.ForeignKey(Parent)
    ... other fields

Now I want to calculate the sum of (field_a * field_b * factor) of all objects in the Child model. I can calculate the sum of (field_a * field_b) with aggregate(value=Sum(F('field_a')*F('field_b'), output_field=DecimalField())). My question is how I can pull out the factor field from the Parent model?

现在我想计算Child模型中所有对象的(field_a * field_b * factor)之和。我可以使用aggregate计算(field_a * field_b)的总和(value = Sum(F('field_a')* F('field_b'),output_field = DecimalField()))。我的问题是如何从父模型中提取因子字段?

I am new to Django and I really appreciate your help!

我是Django的新手,非常感谢你的帮助!

1 个解决方案

#1


5  

Django let's you follow relationships with the double underscore (__) as deep as you like. So in your case F('parent__factor') should do the trick.

Django让你跟随双下划线(__)的关系尽可能深。所以在你的情况下,F('parent__factor')应该这样做。

The full queryset:

完整的查询集:

Child.objects.aggregate(value=Sum(F('field_a') * F('field_b') * F('parent__factor'), output_field=DecimalField()))

#1


5  

Django let's you follow relationships with the double underscore (__) as deep as you like. So in your case F('parent__factor') should do the trick.

Django让你跟随双下划线(__)的关系尽可能深。所以在你的情况下,F('parent__factor')应该这样做。

The full queryset:

完整的查询集:

Child.objects.aggregate(value=Sum(F('field_a') * F('field_b') * F('parent__factor'), output_field=DecimalField()))