简体   繁体   中英

Django - Sort a list by related fields

My models:

Item:
    name
    desc

Type:
    name

Value:
    item.ForeignKey(Item)
    type.ForeignKey(Type)
    val.CharField # varchar or numeric

Now I have an objects list of items but not a QuerySet, for instance: items = [<object:1>, <object:2>, <object:4>] . And t = 5 is an id of a row from Type.

I want to sort this list by val of table Value and type of value is t . Any idea?

Thanks alot!

UPDATE:
- I've added a new condition.

You can always use lambda function to sort the list of items (assuming there is a one to one relationship between Item and Value model, otherwise I don't think the question makes sense)

 items.sort(key=lambda object: object.value_set.all()[0].val)

Although the point to be noted is that the sorting will be in memory.

For Updated Question

Just adding a filter should do the task

 items.sort(key=lambda object: object.value_set.filter(type__id=5)[0].val)
sorted(items.objects.all(), key=lambda item: item.value_set.get().val if item.value_set.all() else None)

如果未为某些项目设置外键,则应这样做。

我在python文档中找到的此类排序教程中的Check Key Functions

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