我有一个问题让我的django订购工作。当我在模型定义中定义一个函数时,它返回一个调用了order_by()
的QuerySet,我得到了正确的顺序。但是,当我在定义之外调用order_by()
时,我没有得到正确的顺序。
以下按名称正确命令'部分':
# models.py
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True, default=0)
...
def get_parts_as_owner(self):
user=self.user
return Part.objects.filter(Q(owner=user)).order_by('name')
class Part(models.Model):
name = models.CharField(max_length=45,unique=True)
last_modified = models.DateTimeField(auto_now=True)
owner = models.ForeignKey(User)
# views.py
def view_parts(request):
user = request.user
owned = user.get_profile().get_parts_as_owner()
return render_to_response('parts/view_parts.html', {'owned': owned}, RequestContext(request))
以下没有按照我的预期(按名称)订购:
# models.py
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True, default=0)
...
def get_parts_as_owner(self):
user=self.user
return Part.objects.filter(Q(owner=user))
class Part(models.Model):
name = models.CharField(max_length=45,unique=True)
last_modified = models.DateTimeField(auto_now=True)
owner = models.ForeignKey(User)
# views.py
def view_parts(request):
user = request.user
owned = user.get_profile().get_parts_as_owner().order_by('name')
return render_to_response('parts/view_parts.html', {'owned': owned}, RequestContext(request))
以下命令按名称而不是last_modified,我希望
# models.py
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True, default=0)
...
def get_parts_as_owner(self,order='name'):
user=self.user
return Part.objects.filter(Q(owner=user)).order_by(order)
class Part(models.Model):
name = models.CharField(max_length=45,unique=True)
last_modified = models.DateTimeField(auto_now=True)
owner = models.ForeignKey(User)
# views.py
def view_parts(request):
user = request.user
owned = user.get_profile().get_parts_as_owner(order='last_modified')
return render_to_response('parts/view_parts.html', {'owned': owned}, RequestContext(request))
为什么这些没有像我期望的那样订购?我打电话给order_by
时有什么不同?
答案 0 :(得分:0)
您应该使用相关的管理器而不是在模型上创建方法来返回一个全新的查询集。例如,要获取用户的部件,您只需执行以下操作:
request.user.get_profile().part_set.order_by('name')
这是内置的。没有必要做任何其他事情。