Search code examples
pythondjangomodels

How can I access a model that is instantiated later for a calculation in Django?


I am fairly new to Python/Django and I have the following problem. I have structured my models as follows:

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)

The relations are that 1 Foo has multiple Bars and 1 Bar has multiple FooBaroos. What I want is to create a table with Django wherein I have a complete overview of a Bar class. One of the things I want to display is the sum of all FooBarooInts of a Bar. If I however add a property to Bar that takes all relevant FooBaroo objects (through objects.all().filter()) it ends up not returning anything in most cases, but not all (which I find weird).

Does anybody have an idea of how I should solve this?


Solution

  • Make use of the related_name and aggregation:

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