A. Innokentiev
A. Innokentiev

Reputation: 721

How to aggregate QuerySet based on property of model?

For example some model:

class Foo(models.Model):
    a = models.FloatField()
    b = models.FloatField()

    @property
    def c(self):
        return self.a / self.b

And we want to find minimal value in QuerySet:

bar = Foo.objects.aggregate(Min('c'))

But this doesn't work, because c not in database and can't be fetched from db. How to get minimum value c of Foo?

Upvotes: 0

Views: 336

Answers (1)

solarissmoke
solarissmoke

Reputation: 31404

You have to do the logic inside the query itself instead of as a property that is evaluated in Python. Something like this should work:

from django.db.models import F, Min

bar = Foo.objects.annotate(c=F('a') / F('b')).aggregate(Min('c'))

Upvotes: 2

Related Questions