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)
Check Key Functions in this sort tutorial that I found in python docs
sorted(items.objects.all(), key=lambda item: item.value_set.get().val if item.value_set.all() else None)
should do it in case your foreign key isn't set for some items.
精彩评论