我一直在尝试执行原始查询并将其映射到字典。
虽然execute_sql
不返回列名,但返回元组。
我使用原始查询,但返回无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的结果
答案 0 :(得分:1)
也许有更好的方法,但是将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)