[Django]-Django order queryset by OnetoOneField

9👍

You can follow OneToOneFields and other foreign key relations by using a double underscore (__):

UserProfile.objects.all().order_by('user__full_name')

This acts a bit similar to how in Python one usually obtains (chains of) attributes. For example if the User has a OneToOneField to (for example) an Office model, then we can for instance query with user__office__floor to sort the users by the floor where their office is located.

Mind that this only works given we are working with fields. So if you would for instance have a User class with a first_name and a last_name, and you use a @property for the full_name (in other words, the full_name is determined when needed), then this will not work, and you will have to sort at Python level. This is logical, since the database of course does not know anything about the Django ORM layer and hence it can not interpret what this property is doing.

Leave a comment