How to sort a queryset based on objects' foreign key by sorted method?

Question:

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?

Asked By: Alston

||

Answers:

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.

Answered By: Sunderam Dubey
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.