Django ORM:对原始查询集应用排序

时间:2016-04-20 11:33:22

标签: django django-queryset django-orm

这是原始查询集Django ORM:

ob = Shop.objects.raw('SELECT * from shops GROUP BY
 (duplicate_field_name) having COUNT(*) = 1 ORDER BY some_field')

listorder = ["check_in","check_out","location"]

此listorder部分是动态的。我不知道它会怎样。它会不时地改变排序&还有一件事不能对原始查询集进行排序,因为我希望将整个数据用于其他目的。之后只有我才能应用排序。 这里要按列表“listorder”排序。

mObj = ob.order_by[*listorder]

在上面面临的错误就像无法对原始查询集进行排序。 有什么想法吗?

1 个答案:

答案 0 :(得分:0)

如果希望按不同字段对原始查询集进行排序,可以将它们添加到ORDER BY子句中。

ob = Shop.objects.raw('SELECT * from shops GROUP BY
 (duplicate_field_name) having COUNT(*) = 1 ORDER BY check_in, check_out, location')

如果您希望特定字段的订单被撤消,您可以将其更改为

ob = Shop.objects.raw('SELECT * from shops GROUP BY
 (duplicate_field_name) having COUNT(*) = 1 ORDER BY check_in, check_out DESC, location')

如果排序是动态的,您可以动态创建查询字符串。

qs = ''SELECT * from shops GROUP BY
 (duplicate_field_name) having COUNT(*) = 1'

# some other code here to decide what your ordering is example
order_fields = ['id','location','check_in','check_out']

qs = qs + "ORDER BY " + ",".join(order_fields)

然后你可以像以前一样查询

Shop.objects.raw(qs)