问题描述
如何在Django QuerySet
中定义特定的顺序?
具体来说,如果我有一个 QuerySet
像这样: ['a10','a1','a2']
。
定期订单(使用 Whatever.objects.order_by('someField')
)将给我 ['a1' 'a10','a2']
,而我正在寻找: ['a1','a2','a10']
/ p>
定义自己的排序技术的正确方法是什么?
据我所知,没有办法以这种方式指定数据库端的排序,因为它也是后端特定的。你可能希望诉诸于古老的Python排序:
class Foo(models.Model):
name = models.CharField(max_length = 128)
Foo.objects.create(name ='a10')
Foo.objects.create(name ='a1')
Foo .objects.create(name ='a2')
ordered = sorted(Foo.objects.all(),key = lambda n:(n [0],int(n [1:]) ))
打印订单#产生a1,a2,10
如果你发现自己需要这个一些排序很多,我建议为执行排序的模型制定一个定制的 models.Manager
子类。类似于:
class FooManager(models.Manager):
def in_a_number_order(self,* args,** kwargs ):
qs = self.get_query_set()。filter(* args,** kwargs)
return sorted(qs,key = lambda n:(n [0],int(n [1: ))
class Foo(models.Model):
...如前所述...
objects = FooManager()
打印Foo .objects.in_a_number_order()
print Foo.objects.in_a_number_order(id__in = [5,4,3])#或任何过滤表达式
How do you define a specific ordering in Django QuerySet
s?
Specifically, if I have a QuerySet
like so: ['a10', 'a1', 'a2']
.
Regular order (using Whatever.objects.order_by('someField')
) will give me ['a1', 'a10', 'a2']
, while I am looking for: ['a1', 'a2', 'a10']
.
What is the proper way to define my own ordering technique?
As far as I'm aware, there's no way to specify database-side ordering in this way as it would be too backend-specific. You may wish to resort to good old-fashioned Python sorting:
class Foo(models.Model):
name = models.CharField(max_length=128)
Foo.objects.create(name='a10')
Foo.objects.create(name='a1')
Foo.objects.create(name='a2')
ordered = sorted(Foo.objects.all(), key=lambda n: (n[0], int(n[1:])))
print ordered # yields a1, a2, 10
If you find yourself needing this kind of sorting a lot, I'd recommend making a custom models.Manager
subclass for your model that performs the ordering. Something like:
class FooManager(models.Manager):
def in_a_number_order(self, *args, **kwargs):
qs = self.get_query_set().filter(*args, **kwargs)
return sorted(qs, key=lambda n: (n[0], int(n[1:])))
class Foo(models.Model):
... as before ...
objects = FooManager()
print Foo.objects.in_a_number_order()
print Foo.objects.in_a_number_order(id__in=[5, 4, 3]) # or any filtering expression
这篇关于在Django定制订购的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!