1

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?

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
Alston
  • 2,085
  • 5
  • 30
  • 49
  • Does this answer your question? [django-orm case-insensitive order by](https://stackoverflow.com/questions/3409047/django-orm-case-insensitive-order-by) – Thom Wiggers Mar 15 '23 at 10:12
  • 1
    @ThomWiggers NO, I don't want to use Django's orm order_by query. I want to tuse sorted() method – Alston Mar 15 '23 at 10:23

1 Answers1

0

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.

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
  • But the sorting result remains old. – Alston Mar 15 '23 at 10:22
  • @Alston If the sorting result is still old, it's possible that the `Course` objects in your queryset don't have a related `Subject` object, try to use `select_related()`, see edited answer. – Sunderam Dubey Mar 15 '23 at 10:28
  • 1
    It works! I forgot sorted() will return a new qs instead of just sorting the original one. THANKS! I'm so stupid... You don't have to add select_related! It's all because I forgot to catch the new return qs. – Alston Mar 15 '23 at 10:43