How to order queryset with lookup fields?

Viewed 104

I want to order my users with their full_name from profile model. How can I do it here ?

views

CustomUser.objects.filter(is_active=True).order_by('profile.full_name')

models

class Profile(models.Model):
    user = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
    full_name = models.CharField(max_length=255)
1 Answers

You look "through" a relation with double underscores (__), so you can order with:

CustomUser.objects.filter(is_active=True).order_by('profile__full_name')

This will make a JOIN in the database, and thus order on the full_name field of the related profile.

Related