Reputation: 2452
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
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 Balance
s that have the given name.
If you want to sort in descending order (so from larger count
s to smaller count
s), then you should add a minus (-
):
Account.objects.filter(
balance__name='my_balance_name'
).order_by('-balance__count')
Upvotes: 1