英文:
How to sort a queryset based on objects' foreign key by sorted method?
问题
I'm happy with the instruction to do sorting:
sorted(qs, key=lambda obj: obj.name.lower(), reverse=True)
But as I need to sort the queryset by obj's foreign key's field. It looks invalid with: (Sort won't work! The order didn't change.)
sorted(qs, key=lambda obj: obj.fkname.name.lower(), reverse=True)
which fkname is the foreign key of the object.
I don't want to do sorting like this:
Course.objects.order_by("subject__name")[0].name # The course cls has a FK to Subject.
Can this be possible?
英文:
I'm happy with the instruction to do sorting:
sorted(qs, key=lambda obj: obj.name.lower(), reverse=True)
But as I need to sort the queryset by obj's foreign key's field. It looks invalid with: (Sort won't work! The order didn't change.)
sorted(qs, key=lambda obj: obj.fkname.name.lower(), reverse=True)
which fkname is the foreign key of the object.
I don't want to do sorting like this:
Course.objects.order_by("subject__name")[0].name # The course cls has a FK to Subject.
Can this be possible?
答案1
得分: 0
可以使用Python中的sorted()
函数基于对象的外键对查询集进行排序。请尝试以下示例:
qs = Course.objects.select_related("subject").all()
sorted_qs = sorted(qs, key=lambda obj: obj.subject.name.lower(), reverse=True)
在这个示例中,qs
是一个要按照相关的Subject
对象的name
字段进行排序的Course
对象的查询集。
sorted()
函数中的reverse
参数指定了排序顺序。如果它为True
,查询集将按降序排序。
英文:
Yes, you can also sort a queryset based on objects' foreign key using the sorted()
function in Python, try the following example:
qs = Course.objects.select_related("subject").all()
sorted_qs = sorted(qs, key=lambda obj: obj.subject.name.lower(), reverse=True)
In this example, qs
is a queryset of Course
objects that you want to sort by the name
field of the related Subject
object.
The reverse
parameter in the sorted()
function specifies the sorting order. If it's True
, the queryset will be sorted in descending order.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论