2012-05-07 12 views
6

Tôi có mô hình Người dùng và mô hình UserProfile. Trong mô hình Người dùng, tôi muốn đặt hàng truy vấn của mình để truy vấn của nó theo thứ tự bảng chữ cái của last_name. Sau đó, tôi muốn đặt hàng nó bằng thuộc tính User_profiles "title" (Manager, Executive, Accountant, vv).DJANGO: Cách sắp xếp các đối tượng dựa trên thuộc tính của một mô hình liên quan?

NGƯỜI MẪU:

from django.contrib.auth.models import User 

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

XEM:

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)) 

"Tiêu đề" không phải là một thuộc tính của mô hình dùng, nhưng có liên quan đến tài khoản của mô hình UserProfile. Làm cách nào để sắp xếp theo thứ tự bảng chữ cái cho UserProfile.title?

Trả lời

9
User.objects.order_by('last_name', 'userprofile__title') 
+0

bạn thưa bạn, thật tuyệt vời! cảm ơn! – thedeepfield