从两个查询的输出djang创建嵌套json

2024-04-20 07:23:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码片段如下所示:

在视图.py在

def get_milestonebased_deals(request):

           cursor = connection.cursor()
           cursor.execute("SELECT id,deal_title, milestone_order_id  from myapp_milestone")
           row = cursor.fetchall()
           cursor2=connection.cursor()
           cursor2.execute("select id, title, deal_milestone_id created from myapp_deals")
           row2=cursor2.fetchall()
           data_dict = ValuesQuerySetToDict(row)
           data_json = json.dumps(data_dict)
           data_dict2 = ValuesQuerySetToDict(row2)
           data_jsonn = json.dumps([data_dict2])
           return json_response({
                               'status':data_json,

                          })

我想从上面的函数创建json对象,如下所示:

^{pr2}$

有人能建议一下吗?如果有,那怎么办?在


Tags: fromidjsonexecutedatatitleconnectioncursor
1条回答
网友
1楼 · 发布于 2024-04-20 07:23:27

对于这个问题,我想到了两种解决方案:

  1. Using django-rest-framework nested serializers
  2. 以下提供的样品:

首先,您应该读取记录中的myapp_deals和{},并向每个记录添加对应的milestone,然后转储整个列表

我提供了一个带有sqlite和我的表header和{}的简单示例。在

It's written in simple python but you can use code in your django view

import sqlite3
import json

def dict_factory(cursor, row):
    '''
    Provides DictCursor for sqlite
    '''
    d = {}
    for idx, col in enumerate(cursor.description):
        d[col[0]] = row[idx]
    return d

conn = sqlite3.connect('db.sqlite')
conn.row_factory = dict_factory
cur = conn.cursor()
cur.execute('''SELECT * FROM HEADER''')
headers_list = list(cur.fetchall())
for header in headers_list:    
    cur.execute('SELECT * FROM DETAIL WHERE HEADER_ID=' + str(header['id']))
    row = cur.fetchone()
    if row is not None:
       header['details'] = row
cur.close()

print(json.dumps(headers_list))

结果:

^{pr2}$

相关问题 更多 >