Django:RunSQL:使用PostgreSQL COPY命令

gue*_*tli 10 django postgresql psycopg2 database-migration

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

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

它失败了:

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
Run Code Online (Sandbox Code Playgroud)

COPY不允许RunSQL吗?

我们使用psycopg2

bim*_*api 6

psycopg2驱动程序公开copy_tocopy_from可用于实现相同的行为方式psql的客户端; 关键是用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)
    ]
Run Code Online (Sandbox Code Playgroud)

一些注意事项:

  • file传递给的对象copy本质上STDIN是在语句中。
  • 复制命令可能对列很挑剔;使用copy_expert您可以控制所有与命令相同的选项:格式、标题、分隔符等。

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