3

I have two models that go as follows (for simplicity's sake):

class Bank(models.Model):
    name = models.CharField(max_length=250)


class Person(models.Model):
    bank = models.ForeignKey(Bank)
    savings = models.IntegerField()
    debts = models.IntegerField()

    def get_net_worth(self):
        return self.savings - self.debts

And I want to write a method that lets me know the "total net worth" of the people in a bank, like:

class Bank(models.Model):
    ...
    def get_net_worth(self):
        return self.person_set.all().aggregate(Sum('get_net_worth'))

But of course Django complains that such field does not exist:

django.core.exceptions.FieldError: Cannot resolve keyword 'get_net_worth' into field.

Is there a way to achieve this without having to explicitly store the "net worth" in the database?

Edit:

In case you wonder, one can just do

def get_net_worth(self):
    person_queryset = self.person_set.all()
    return person_queryset.aggregate(Sum('savings'))['savings__sum'] - person_queryset.aggregate(Sum('debts'))['debts__sum']

But I do have to somehow use the get_net_worth method on every "Person".

Edit 2:

Just to clarify things up: These two are not my actual models, they are over-simplified examples of what I want to achieve, and what I essentially want to do is NOT to do arithmetic between two fields, but rather use a model's method as the field for the aggregate function (of course a method can do some more complex stuff before returning a value), therefore this one is not a duplicate of the other question.

arielnmz
  • 8,354
  • 9
  • 38
  • 66

0 Answers0