Django: How do I use a foreign key field in aggregation?
<p>Let's say I have the following two models:</p>

<pre><code>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
</code></pre>

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

<p>I am new to Django and I really appreciate your help!</p>

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

<p>The full queryset:</p>

<pre><code>Child.objects.aggregate(value=Sum(F('field_a') * F('field_b') * F('parent__factor'), output_field=DecimalField()))
</code></pre>

python django