Supremus
Supremus

Reputation: 151

Ordering queryset by property of related model with another property equal to something

Let's say i have this model relationship:

class Account(models.model):
   ...

class Balance(models.Model):
    class Meta:
       verbose_name = u"Balance"
       verbose_name_plural = u"Balances"

    name = models.CharField(max_length=200, verbose_name=u"Currency", null=True, blank=True)
    count = models.FloatField(verbose_name=u"Count", null=True, blank=True)
    account = models.ForeignKey(Account, verbose_name='Account', on_delete=models.CASCADE, null=True, blank=True)

    def __str__(self):
       return self.name

I have the queryset of accounts, they all have the same amount of balances and balances have the same names but not the same counts. For example i have 3 accounts, and each account has only 2 related balances with names 'foo' and 'bar', but 'count' property in these balances may differ. How do i order account by 'count' property of its balance with name 'foo'?

Also if possible would like to get solution for this problem but for filtering though i've made kludge for this already using for in so it's not that important.

Upvotes: 0

Views: 67

Answers (1)

VersBersch
VersBersch

Reputation: 193

If every account has a balance with name 'foo' then you could annotate the queryset with the sum of the foo balances then order the query set by that

from django.db.models import Q, Sum

qs = Account.objects.all().annotate(
    foo_count=Sum('balances__count', filter=Q(balances__name='foo'))
).order_by('-foo_count')

Upvotes: 1

Related Questions