Django:RunSQL:使用PostgreSQL COPY命令

时间:2015-08-07 10:38:05

标签: django postgresql database-migration psycopg2

我尝试使用以下RunSQL命令运行迁移:

class Migration(migrations.Migration):
    operations = [
        RunSQL(
r'''
COPY auth_group (id, name) FROM stdin;
1   TEST-GROUP
\.
''')]

它失败了:

File "/home/foo/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 63, in execute
     return self.cursor.execute(sql)
django.db.utils.ProgrammingError: syntax error at or near "1"
LINE 3: 1 TEST-GROUP

COPY中不允许RunSQL吗?

我们使用psycopg2

1 个答案:

答案 0 :(得分:3)

psycopg2驱动程序公开了可用于实现与copy_to客户端相同行为的copy_frompsql方法;关键是使用RunPython操作而不是RunSQL操作。

你需要:

  • 迁移中用于打开文件并与复制方法交互的功能
  • 迁移RunPython列表中的operations操作以调用该功能

示例,使用Django 1.8.4,Python 2.7.10,psycopg2 2.6.1 -

from django.db import models, migrations

def forwards(apps, schema_editor):
    with open('./path/to/file.csv', 'r') as infile:
        with schema_editor.connection.cursor() as stmt:
            #for finer control, use copy_expert instead
            stmt.copy_from(infile, 'your_table', sep=',')

class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
        #this runs your function
        migrations.RunPython(forwards)
    ]

一些注意事项:

  • 传递给file的{​​{1}}对象在声明中基本上是copy
  • 复制命令可能对列很挑剔;使用STDIN,您可以控制与命令相同的所有选项:格式,标题,分隔符等。

有关copy_expert方法的详情,请查看psycopg2文档:http://initd.org/psycopg/docs/cursor.html