phen0menon
phen0menon

Reputation: 2452

Django How to filter and sort queryset by related model

I have this model relationship:

class Account:
    < ... fields ... >


class Balance(models.Model):       
    name = models.CharField(...)
    count = models.FloatField(...)
    account = models.ForeignKey(Account, related_name='balance')

Let's say we have some number of accounts. I need to filter these accounts by balance__name and sort by balance__count. I need sorted accounts, not a list of balances.

How do I do that? I don't even have any suggestions to find out a solution using iteration.

Upvotes: 1

Views: 329

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476544

You can implement a queryset like:

Account.objects.filter(
    balance__name='my_balance_name'
).order_by('balance__count')

Note that here an account can occur multiple times if there are multiple Balances that have the given name.

If you want to sort in descending order (so from larger counts to smaller counts), then you should add a minus (-):

Account.objects.filter(
    balance__name='my_balance_name'
).order_by('-balance__count')

Upvotes: 1

Related Questions