简体   繁体   中英

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.

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM