Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: How do I use a foreign key field in aggregation?

Tags:

python

django

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?

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

like image 286
tianz Avatar asked Sep 26 '16 00:09

tianz


People also ask

How does foreign key work in Django?

ForeignKey is a Django ORM field-to-column mapping for creating and working with relationships between tables in relational databases. ForeignKey is defined within the django. db. models.

How does Django store foreign key values?

Note that the _id in the artist parameter, Django stores foreign keys id in a field formed by field_name plus _id so you can pass the foreign key id directly to that field without having to go to the database again to get the artist object.


1 Answers

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.

The full queryset:

Child.objects.aggregate(value=Sum(F('field_a') * F('field_b') * F('parent__factor'), output_field=DecimalField()))
like image 185
Andreas Avatar answered Sep 30 '22 18:09

Andreas