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
该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)
]
Run Code Online (Sandbox Code Playgroud)
一些注意事项:
file传递给的对象copy本质上STDIN是在语句中。copy_expert您可以控制所有与命令相同的选项:格式、标题、分隔符等。有关这些copy_*方法的更多信息,请查看 psycopg2 文档:http : //initd.org/psycopg/docs/cursor.html
| 归档时间: |
|
| 查看次数: |
1004 次 |
| 最近记录: |