django 如何在postgresql中使用python将一个表中的列数据添加到另一个表的列字段中

mgdq6dx1  于 2022-11-18  发布在  Go
关注(0)|答案(1)|浏览(157)

我是django和postgresql的新手。我在postgresql中有两个表。在一个表中,我有两个字段ID和Value。我想将ID列中的数据添加到另一个名为value_id的表列字段中。在postgres中,这些表来自同一个模式。我想通过python完成此操作。有没有办法。请帮助。

cur = con.cursor()

    db_insert = """INSERT INTO "Database"."TABLE_ONE"
    ("LT_ID_ONE", "LT_ID_TWO")  
    VALUES(
    (SELECT "LT_ID_ONE" FROM "Database"."TABLE_TWO" WHERE "LT_NUM_ONE" =%s), 
    (SELECT "LT_ID_TWO" FROM "Database"."TABLE_THREE" WHERE "LT_NUM_TWO" =%s)
    );"""
    insert_values = (df1.iloc[0, 0], df1.iloc[0, 1])

    cur.execute(db_insert, insert_values)

我在django中这样做,所以上面的方法将不起作用。任何人都可以建议任何方法吗?

oiopk7p5

oiopk7p51#

您可以使用迁移文件执行此操作,

class Migration(migrations.Migration):

    dependencies = [
        ( .....),
    ]
    operations = [
        migrations.AddField(
            model_name="Model1",
            name="field1",
        ),
        migrations.RunPython(forwards_migrate_data_from_field2_to_field1,reverse_migrate_data_from_field2_to_field1),
        migrations.RemoveField(
            model_name='model2',
            name='field2'
        )
    ]

并且在forwards_migrate_data_from_field2_to_field1函数中,你需要做移动数据的过程,请在django docs中查看此链接:https://docs.djangoproject.com/en/4.1/ref/migration-operations/#runpython

def forwards_migrate_data_from_field2_to_field1(apps, schema_editor):
    # we move from model2 to model1
    model2 = apps.get_model("app", "model2")
    model1 = apps.get_model("app", "model1")
    db_alias = schema_editor.connection.alias
    list_field2 = (
        models2.objects.using(db_alias)
        .all()
        .values_list("field2",)
    )
    model1.objects.using(db_alias).bulk_create(
        [
            model1(
                field2=field2,
            )
            for field2 in list_field2
        ]
    )

相关问题