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

I have a User model and UserProfile. In the User model, I would like to order my request to have it alphabetically by last_name. Then I would like to order it using the "title" attribute of User_profiles (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)) 

The "name" is not an attribute of the user model, but is associated with the user according to the UserProfile model. How to sort alphabetically for UserProfile.title?

+6
source share
1 answer
 User.objects.order_by('last_name', 'userprofile__title') 
+9
source

Source: https://habr.com/ru/post/915123/


All Articles