是Django QuerySet的`order_by`方法添加剂吗?

时间:2013-11-20 19:48:10

标签: django django-queryset

鉴于以下模型和查询,如果多次调用order_by(),将产生什么查询?

class MyModel(models.Model):
    field_a = models.IntegerField()
    field_b = models.IntegerField()

qs = MyModel.objects.all().order_by('field_a')
qs = qs.order_by('field_b')

qs生成什么SQL?

ORDER BY field_a, field_b

ORDER BY field_b

也就是说,对[{1}} 的后续调用是否覆盖以前的来电,还是添加到这些来电?

1 个答案:

答案 0 :(得分:1)

答案是,后续调用order_by 覆盖之前的调用:

In [7]: print MyModel.objects.all().order_by('field_a').order_by('field_b').query
SELECT "mymodel"."id", "mymodel"."field_a", "mymodel"."field_b" 
FROM "mymodel" 
ORDER BY "mymodel"."field_b" ASC