【发布时间】:2017-10-05 22:26:23
【问题描述】:
我正在 django 中使用原始 SQL 进行复杂查询,以解决一些注释问题。 实际查询中有许多左连接已被转换为子查询,以解决 Django 中的一个主要错误。 https://code.djangoproject.com/ticket/10060
给定
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(*fields) 我做了类似的事情
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,*fields)
【问题讨论】:
-
在使用
objects.raw时,我有类似的要求来获取元组/字典列表。您是否碰巧找到了干净的解决方案? -
我在 hynekcer 的回答中使用了该模式!
标签: python django django-queryset