我正在编写一个 Django 命令来为现有表播种,
我需要在播种之前截断表,但该表上有外键约束。
因此,我得到django.db.utils.IntegrityError截断表格时,
如何在 Django 中暂时关闭外键检查?
I saw 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')
得到了解决方案。
我必须禁用表上的触发器才能停止外键约束检查。
禁用触发器
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;')
重要笔记:
-
根据这个文档链接 https://docs.djangoproject.com/en/2.1/topics/db/sql/#connections-and-cursors,您可以将列表作为第二个参数传递给execute()
方法(例如:您可能想要动态传递表名),但这会自动转义变量,您最终可能会形成语法错误的 PostgreSQL 查询(这花了我很多时间来修复它)
-
确保正确重新打开触发器
-
如果您得到的是权限被拒绝错误然后你可能想检查数据库用户权限,我刚刚从 PgAdmin 打开了超级用户权限,这对我来说没问题。一切都恢复正常。怎么做 ? https://stackoverflow.com/a/52768479/2693543
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)