如何使用`sorted`方法根据对象的外键对查询集进行排序?

huangapple go评论136阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年3月15日 18:00:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/75743127.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定