Micah Pearce
Micah Pearce

Reputation: 1965

Django order queryset by OnetoOneField

I have a two models UserProfile and User. The UserProfile model has a onetoone filed with the user. I figured out how to order the UserProfile by a variable it contains. However, I do not know how to order the items in UserProfile by their related User models

class User(AbstractBaseUser):
    full_name   = models.CharField(max_length=255, blank=True, null=True)

class UserProfile(models.Model):
    user                = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
    lunch_price         = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True)

I can run this query just fine:

from myapp.models import UserProfiles
print(UserProfile.objects.all().order_by('lunch_price')

I thought i'd run something like this to order by full_name, but it doesn't work

from myapp.models import UserProfiles
print(UserProfile.objects.all().order_by('user.full_name')

How do I make that jump to the user model?

Upvotes: 3

Views: 1382

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477824

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.

Upvotes: 9

Related Questions