Peewee 和插入列表

Peewee and Inserts with lists

我对如何使用 Peewee 将元组列表插入数据库感到困惑。我的数据库设置如下:

class Stats(Model):
    name = TextField(index=True)
    gender = TextField()
    age = TextField()
    city = TextField()
    state = TextField()

    class Meta:
        database = db

我的元组列表如下所示:

records = [("Joe Smoe", "Male", 34, "Joe City", "Joe State")],
          [("Jane Doe", "Female", 21, "Jane City", "Jane State")]

我是否遍历列表一次插入一行?这可以批量插入还是需要将其制成字典才能做到这一点?

可以 遍历列表并一次插入一行,但是使用 peewee 的 Model.insert_many 函数进行批量操作要好得多,效率也要高得多使用单个 SQL INSERT 语句插入。是的,根据那些 API 文档,insert_many() 需要 dict 对象的列表(或任何可迭代的),每个对象都必须具有相同的键。

您可以手动执行此操作,如下所示:

rows = [
    {"name": "Joe Smoe", "gender": "Male", "age": 34,
     "city": "Joe City", "state": "Joe State"},
    {"name": "Jane Doe", "gender": "Female", "age": 21,
     "city": "Jane City", "state" :"Jane State"},
    ...
]
Stats.insert_many(rows)

或者如果您已经有了一个 records 元组列表,就像您在问题中显示的那样,您可以使用 Model._meta.sorted_field_names 迭代 Stats 模型的字段名称以构建口述:

# Be sure to exclude the implicit primary key field
fields = [name for name in Stats._meta.sorted_field_names if name != 'id']
rows = [dict(zip(fields, record)) for record in records]
Stats.insert_many(rows)

我最后只是获取了各个列表,并对它们使用 dict comp 将它们转换为一个 dict 以便插入。所以它看起来像这样:

name_list = ['Joe Smoe', 'Jane Doe']
gender_list = ['male', 'female']
age_list = [34, 21]
city_list = ['Joe City', 'Jane City']
state_list = ['Joe State', 'Jane State']

completed_dict = [{
                 'name': a, 'gender': b, 'age': c, 'city': d, 'state': e}
                 for a, b, c, d, e, in zip(name_list, gender_list,  age_list, city_list, state_list)]

with db.atomic():
    Stats.insert_many(completed_dict).execute()

不确定这是否是最好的方法,但对我来说效果很好。