gpt4 book ai didi

python - 在 django 中迁移后运行 .sql 文件

转载 作者:太空宇宙 更新时间:2023-11-04 06:59:50 25 4
gpt4 key购买 nike

我已经在 Django 中设置了迁移(非常小的项目);但我有一个 .sql 文件,其中包含数据库中我需要的大量数据。

在运行迁移之后/期间执行此 .sql 文件的最佳方式(或者甚至可能)是什么?

sql 文件只包含插入的数据,如下所示:

INSERT INTO `mileages_mileages` (`id`, `miles`, `start_location`, `end_location`) VALUES
(NULL,3, 'Location 1', 'Location 2'),

我只需要在运行模型的初始迁移后执行该 .sql 文件。

这可能吗?

最佳答案

migrations.RunSQL()

不接受文件作为输入。只有原始 SQL。要解决此问题,您需要使用:

migrations.RunSQL(
"""
INSERT INTO 'mileages_mileages' ('id', 'miles', 'start_location', 'end_location')
VALUES
(NULL,3, 'Location 1', 'Location 2');
""")

def load_data_from_sql(apps, schema_editor):
file_path = os.path.join(os.path.dirname(__file__), 'file_name.sql')
sql_statement = open(file_path).read()
with connection.cursor() as c:
c.execute(sql_statement)

class Migration(migrations.Migration):
dependencies = [
('..', '...'),
]

operations = [
migrations.RunPython(load_data_from_sql),
]

关于python - 在 django 中迁移后运行 .sql 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44114931/

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