我正在用django中的原始SQL做一个复杂的查询来解决一些注解问题。 实际的查询有很多左连接已被转换为子查询,以避开Django中的主要错误。 https://code.djangoproject.com/ticket/10060如何从Django RawQuerySet获取元组列表?
鉴于
fields = ['shift__adminFee',
'shift__rosterSlot__adminFee',
'shift__taxi__rosterGroup__adminFee',
'shift__driver__adminFee']
query = `''select table.id, "table_shift"."adminFee"
, "table_rosterslot"."adminFee"
, "table_rostergroup"."adminFee"
, "table_driver"."adminFee" from table
left join (select table_id, sum(amount) amount_sum from related_table group by table_id) related_table
on table.id = related_table.table_id
...
(more inner joins and tables to support the above fields)
'''
rawQuerySet = Table.objects.raw(q)
它返回一个RawQuerySet。
RawQuerySet运行良好......并且它填充相关模型以及给出正确的带注释的结果。
然而,RawQuerySet不支持返回元组列表。
我已经看过源文件,在项目中本地是'env/lib/python2.7/site-packages/django/db/models/query.py' 但我还不明白并且我得到了一个结果。
因此而不是做results_as_list_of_tuples = query.values_list(*字段) 我不喜欢的东西
results_as_list_of_tuples = []
for result in query:
shift = result.shift
eventSchedule = shift.eventSchedule
rosterSlot = shift.rosterSlot
taxi = shift.taxi
rosterGroup = taxi.rosterGroup
data = []
...
# the following is one line. I broke it up because it didn't format correctly.
data.extend([
shift.adminFee
,rosterSlot.adminFee
,rosterGroup.adminFee
,driver.adminFee]
)
...
results_as_list_of_tuples.append(tuple(data))
如何从一个Django RawQuerySet得到一个元组列表与 像results_as_list_of_tuples = values_list(raw_query_set, *字段)