Skip to main content
 首页 » 编程设计

python之如何从 Django RawQuerySet 中获取元组列表

2024年10月01日27落叶无声

我在 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)

请您参考如下方法:

您可以通过 columns 属性从 RawQuerySet 获取列名列表。 values_list 迭代器可以通过这种方式从原始查询集创建:

def raw_queryset_as_values_list(raw_qs): 
    columns = raw_qs.columns 
    for row in raw_qs: 
        yield tuple(getattr(row, col) for col in columns) 

columns 属性未记录,但稳定。