Skip to content
Advertisement

How to join linked models with foreign key?

I’m coming from Java and new to python / django. So may be my question is silly …

I have one class Parent which contains an association with a class Child.

class Parent(models.Model):
    pass
    
class Child(models.Model):
    value = models.DecimalField(decimal_places=2, max_digits=12,default=0.0);
    parent = models.ForeignKey(Parent, on_delete=models.CASCADE, null=True, related_name='children')

Parent refers to its ‘Childs’ through the related name ‘children’. At Run time it works well, but at design time, it isn’t reachable from the declaration of the class Parent.

If I want the parent to get a summarized value of its children, the best option I found is to first get the set of children and then to summarize from it

class Parent(models.Model):
@property
def total_value(self):
    return float(Child.objects.filter(parent=self).aggregate(Sum('value'))['value__sum']) or 0.00
pass

Do you know if there is a better way to do this? Can’t we imagine something like:

children.aggregate(Sum('value'))

In other words: is it possible to directly access the children from the Parent (at design time) without making a query?

Advertisement

Answer

You can always treat the same way this two:

Child.objects.filter(parent=self)
self.children.all()

But first you have to have some Parent object. Inside class’ methods of Parent it’s self, otherwise it’s something like:

parent = Parent.objects.get(id=1)
parent.children.all()

So basically this should work:

self.children.aggregate(Sum('value'))['value__sum']

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement