gpt4 book ai didi

python - 如何将 Pandas Dataframe 写入 Django 模型

转载 作者:太空狗 更新时间:2023-10-29 17:55:22 25 4
gpt4 key购买 nike

我一直在 python 中使用 pandas,我通常将数据帧写入我的数据库表,如下所示。我现在正在迁移到 Django,如何通过名为 MyModel 的模型将相同的数据帧写入表?非常感谢您的帮助。

# Original pandas code
engine = create_engine('postgresql://myuser:mypassword@localhost:5432/mydb', echo=False)
mydataframe.to_sql('mytable', engine,if_exists='append',index=True)

最佳答案

我现在正在做同样的练习。我采用的方法是从 DataFrame 创建一个新对象列表,然后是 bulk create他们:

bulk_create(objs, batch_size=None)

This method inserts the provided list of objects into the database in an efficient manner (generally only 1 query, no matter how many objects there are)

一个例子可能是这样的:

# Not able to iterate directly over the DataFrame
df_records = df.to_dict('records')

model_instances = [MyModel(
field_1=record['field_1'],
field_2=record['field_2'],
) for record in df_records]

MyModel.objects.bulk_create(model_instances)

关于python - 如何将 Pandas Dataframe 写入 Django 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34425607/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com