Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Course.objects.order_by("subject__name")[0].name  # The course cls has a FK to Subject.

Can this be possible?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading