Don
Don

Reputation: 125

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?

Upvotes: 1

Views: 57

Answers (3)

user2390182
user2390182

Reputation: 73450

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

Upvotes: 1

Kamran Hosseini
Kamran Hosseini

Reputation: 536

I think you can use this:

obj.foobaroo_set.values_list('FooBarooInts')

In the above "obj" is a custom Bar that you want to sum it's FooBarooInts. Notice that foobaroo_set must be lowercase ( even your model name is not).

You can see more details here and here.

Upvotes: 0

Marin
Marin

Reputation: 1121

query = FooBaroo.objects.filter(Barkey={some_id}).all() # List all values
query_sum = FooBaroo.objects.filter(Barkey={some_id})..aggregate(Sum('Barkey')) # Query to sum

Upvotes: 0

Related Questions