Django:RunSQL:使用 PostgreSQL COPY 命令

Django: RunSQL: use PostgreSQL COPY command

我尝试 运行 使用以下 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

RunSQL中是否有COPY不允许的?

我们使用psycopg2

psycopg2 driver 公开了 copy_tocopy_from 方法,可用于实现与 psql 客户端相同的行为;关键是使用 RunPython 操作而不是 RunSQL 操作。

你需要:

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

示例,使用 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)
    ]

一些注意事项:

  • 传递给copyfileobject本质上就是STDIN语句中的
  • 复制命令可以对列进行挑剔;使用 copy_expert 您可以控制与命令相同的所有选项:格式、headers、定界符等

有关 copy_* 方法的更多信息,请查看 psycopg2 文档:http://initd.org/psycopg/docs/cursor.html