代码之家  ›  专栏  ›  技术社区  ›  Shobi

如何临时禁用django-postgresql中的db完整性约束

  •  0
  • Shobi  · 技术社区  · 7 年前

    我正在编写一个Django命令来为一个现有表播种,

    我需要在设定种子之前截断该表,但该表上存在外键约束。

    django.db.utils.IntegrityError文件 在截断表时,

    SET FOREIGN KEY CHECK = 0 但不知道放在哪里:(

    Django命令类:

    class Command(BaseCommand):
    help = "Command to seed the aws regions"
    regions = [
        {
            'name': 'Us East (N. Virginia)',
            'region': 'us-east-1',
        },
        {
            'name': 'US West (Oregon)',
            'region': 'us-west-2',
        },
        {
            'name': 'EU (Ireland)',
            'region': 'eu-west-1',
        },
    ]
    def handle(self, *args, **options):
        self.stdout.write('seeding regions...')
    
        AwsRegions.objects.all().delete() # this is where i get errors
    
        for name, region in self.regions:
            self.stdout.write(region)
            AwsRegions.objects.create(name, region)
    
    
        self.stdout.write('done seeding regions')
    
    2 回复  |  直到 7 年前
        1
  •  4
  •   Shobi    7 年前

    找到解决办法了。

    我不得不禁用表上的触发器来停止外键约束检查。

    禁用触发器

    def disable_triggers(self):
            with connection.cursor() as cursor:
                cursor.execute('ALTER TABLE "Table Name" DISABLE TRIGGER ALL;')
    

    启用触发器

    def enable_triggers(self):
        with connection.cursor() as cursor:
            cursor.execute('ALTER TABLE "Table Name" ENABLE TRIGGER ALL;')
    

    :

    • this doc link execute() 方法(例如:您可能希望动态传递表名),但这将自动转义变量,最终可能会形成语法错误的PostgreSQL查询(这花费了我很多时间来修复)

    • 确保你正确地打开触发器

    • 权限被拒绝错误 然后你可能想检查DB用户权限,我刚刚从PgAdmin打开了超级用户权限,这对我来说没问题。一切恢复正常。 How to do it ?
        2
  •  1
  •   Roman Tkachuk    7 年前

    SET session_replication_role TO 'replica'
    

    以及恢复:

    SET session_replication_role TO 'origin'