Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DJANGO: How to sort objects based on attribute of a related model?

I have a User model and UserProfile model. In the User model I'd like to order my query so that its in alphabetical order by last_name. Then I'd like to order it by the User_profiles "title" attribute (Manager, Executive, Accountant etc).

MODELS:

from django.contrib.auth.models import User

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    title = models.CharField(max_length=20)

VIEW:

def user_index(request):
    i = User.objects.all().order_by('last_name', 'title')
    return render_to_response('db/user_index.html', {'i': i ,}, context_instance=RequestContext(request))

"Title" is not an attribute of the User model, but is related to User by the UserProfile model. How can I sort by alphabetical order for UserProfile.title?

like image 671
thedeepfield Avatar asked May 07 '12 19:05

thedeepfield


People also ask

How do you sort a list of objects based on an attribute?

A simple solution is to use the list. sort() function to sort a collection of objects (using some attribute) in Python. This function sorts the list in-place and produces a stable sort. It accepts two optional keyword-only arguments: key and reverse.


1 Answers

User.objects.order_by('last_name', 'userprofile__title')
like image 200
San4ez Avatar answered Oct 13 '22 16:10

San4ez