gpt4 book ai didi

Django 迁移 RunSQL 以数据库类型为条件

转载 作者:行者123 更新时间:2023-12-03 02:00:05 25 4
gpt4 key购买 nike

我正在尝试使用 migrations.RunSQL Django 迁移来运行一些任意 SQL 代码。我想仅针对某些数据库后端运行此迁移(例如仅针对 postgres)。

我想to use something like this但我在 Migration 类中没有看到数据库连接信息。

最佳答案

以下是我解决问题的方法,因为我无法让 RunSQLRunPython 中工作。值得庆幸的是,schema_editor 对象有一个 execute() method .

def forwards(apps, schema_editor):
if not schema_editor.connection.vendor.startswith('postgres'):
logger.info('Database vendor: {}'.format(schema_editor.connection.vendor))
logger.info('Skipping migration without attempting to ADD CONSTRAINT')
return

schema_editor.execute('ALTER TABLE my_table ADD CONSTRAINT my_constraint (my_field != \'NaN\';)')


def backwards(apps, schema_editor):
if not schema_editor.connection.vendor.startswith('postgres'):
logger.info('Database vendor: {}'.format(schema_editor.connection.vendor))
logger.info('Skipping migration without attempting to DROP CONSTRAINT')
return

schema_editor.execute('ALTER TABLE my_table DROP CONSTRAINT my_constraint;')


class Migration(migrations.Migration):

dependencies = [
...
]

operations = [
migrations.RunPython(forwards, backwards, atomic=True)
]

关于Django 迁移 RunSQL 以数据库类型为条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32384547/

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