我一直在尝试执行原始查询并将其映射到字典。
虽然 execute_sql
不返回列名,但它返回元组。
我使用原始查询,但它返回 None Abc 实例
class Abc(BaseModel):
name = CharField()
engine = CharField()
q = Abc.raw('show table status from ' + config.DB['name'])
print(list(q.execute()))
输出:
[<Abc: None>, <Abc: None>, <Abc: None>, <Abc: None>, <Abc: None>, <Abc: None>, <Abc: None>, <Abc: None>, <Abc: None>, <Abc: None>, <Abc: None>, <Abc: None>, <Abc: None>, <Abc: None>, <Abc: None>]
sql的结果
最佳答案
也许有更好的方法,但是使用 execute_sql
和 cursor.description
以及列名,我可以为所有表创建包含字典的列表
import peewee
db = peewee.MySQLDatabase('my_database', user='my_user' password='my_password')
cursor = db.execute_sql('show table status from my_database')
all_tables = []
for row in cursor.fetchall():
table = dict()
for column, value in zip(cursor.description, row):
column_name = column[0]
print(column_name, '=', value)
table[column_name] = value
all_tables.append(table)
print(all_tables)
我的数据库之一的结果:
[
{'Name': 'alembic_version', 'Engine': 'InnoDB', 'Version': 10, 'Row_format': 'Dynamic', 'Rows': 0, 'Avg_row_length': 0, 'Data_length': 16384, 'Max_data_length': 0, 'Index_length': 0, 'Data_free': 0, 'Auto_increment': None, 'Create_time': datetime.datetime(2019, 4, 29, 17, 19), 'Update_time': None, 'Check_time': None, 'Collation': 'latin1_swedish_ci', 'Checksum': None, 'Create_options': '', 'Comment': ''},
{'Name': 'users', 'Engine': 'InnoDB', 'Version': 10, 'Row_format': 'Dynamic', 'Rows': 0, 'Avg_row_length': 0, 'Data_length': 16384, 'Max_data_length': 0, 'Index_length': 65536, 'Data_free': 0, 'Auto_increment': 2, 'Create_time': datetime.datetime(2019, 4, 29, 17, 19), 'Update_time': None, 'Check_time': None, 'Collation': 'latin1_swedish_ci', 'Checksum': None, 'Create_options': '', 'Comment': ''},
{'Name': 'woocommerce', 'Engine': 'InnoDB', 'Version': 10, 'Row_format': 'Dynamic', 'Rows': 0, 'Avg_row_length': 0, 'Data_length': 16384, 'Max_data_length': 0, 'Index_length': 16384, 'Data_free': 0, 'Auto_increment': 3, 'Create_time': datetime.datetime(2019, 4, 29, 17, 19), 'Update_time': None, 'Check_time': None, 'Collation': 'latin1_swedish_ci', 'Checksum': None, 'Create_options': '', 'Comment': ''}
]
<小时/>
编辑:相同,但具有列表理解
import peewee
db = peewee.MySQLDatabase('my_database', user='my_user' password='my_password')
cursor = db.execute_sql('show table status from my_database')
column_names = [x[0] for x in cursor.description]
all_tables = [dict(zip(column_names, row)) for row in cursor.fetchall()]
print(all_tables)
关于python - Peewee - 如何执行原始查询并将其映射到字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56219520/