[英]DJANGO: How to sort objects based on attribute of a related model?
我有一个User模型和UserProfile模型。 在User模型中,我想命令我的查询,使其按last_name的字母顺序排列。 然后我想通过User_profiles“title”属性(经理,执行,会计等)来订购它。
楷模:
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.OneToOneField(User)
title = models.CharField(max_length=20)
视图:
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))
“标题”不是用户模型的属性,而是与UserProfile模型的用户相关。 如何按字母顺序对UserProfile.title进行排序?
User.objects.order_by('last_name', 'userprofile__title')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.