我正在用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, *字段)