我尝试使用以下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
答案 0 :(得分:3)
psycopg2
驱动程序公开了可用于实现与copy_to
客户端相同行为的copy_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)
]
一些注意事项:
file
的{{1}}对象在声明中基本上是copy
。STDIN
,您可以控制与命令相同的所有选项:格式,标题,分隔符等。有关copy_expert
方法的详情,请查看psycopg2文档:http://initd.org/psycopg/docs/cursor.html