如何在django中对具有外键的对象列表进行排序?

时间:2016-11-03 07:43:28

标签: python django sorting

我想根据User余额

Bank个对象列表进行排序

模型用户

Class User(model.Model):
    name,
    birthday
    ...

模型库

Class Bank(model.Model):
    user = model.OneToOneField('user.User')
    balance = model.IntegerField()
    ...

数据

User has 2 objects `Username 1` and `Username2`

Bank has 2 objects:
    - object1:
        - user: user1
        - balance: 5000

    - object2:
        - user: user2
        - balance: 3000

对象列表 user_list

[<User: User 1>, <User: User 2>]

如果我sorted(user_list)它将返回相同的列表,但我希望它基于Bank.balance排序,因此列表应为[<User: User 2>, <User: User 1>]。我该怎么办?

此致

1 个答案:

答案 0 :(得分:0)

users = Bank.objects.all().values_list('user').order_by('balance')