[英]Django (1.7) - data migrations
I have created an empty data migration script for populating one of app db tables with data from a JSON file, using我创建了一个空的数据迁移脚本,用于使用来自 JSON 文件的数据填充应用程序数据库表之一,使用
python manage.py makemigrations --empty <app name>
I want to add data contained in JSON files to the db, which at the moment consists of just one table, using a data migration script (according to Django 1.7 docs this is the recommended approach) using a custom method called populate_db
which will use bulk_create
to add multiple entries to the table, and then do a save()
to write the changes to the db.我想将 JSON 文件中包含的数据添加到 db 中,该数据库目前只包含一个表,使用数据迁移脚本(根据 Django 1.7 文档,这是推荐的方法),使用名为
populate_db
的自定义方法,该方法将使用bulk_create
将多个条目添加到表中,然后执行save()
将更改写入数据库。 At the moment the custom method is empty because I am still working on it, but the script looks like this right now目前自定义方法是空的,因为我仍在处理它,但脚本现在看起来像这样
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def populate_db( apps, schema_editor ):
print ‘Populating db from JSON file...'
class Migration(migrations.Migration):
dependencies = [
('<app name>', '0003_auto_20150224_2024'),
]
operations = [
migrations.RunPython( populate_db ),
]
How do I test this script to make sure the custom method works as expected, before I run it fully?在完全运行该脚本之前,如何测试该脚本以确保自定义方法按预期工作? Can I call this from the interpreter and test it with the db API?
我可以从解释器中调用它并使用 db API 对其进行测试吗?
At the moment if I do目前如果我这样做
python manage.py migrate <app name>
it reports there are no migrations to apply.它报告没有要应用的迁移。
You can migrate backward:您可以向后迁移:
python migrate <app name> 0003
And then run your migration again:然后再次运行您的迁移:
python migrate <app name>
UPDATE : To make the data migration reversible add the reverse_code
argument:更新:要使数据迁移可逆,请添加
reverse_code
参数:
def depopulate_db(apps, schema_editor):
print 'Deleting previously added data from db...'
class Migration(migrations.Migration):
...
operations = [
migrations.RunPython(populate_db, depopulate_db),
]
OK, I found a solution that works: manually deleting the entry in the migrations
db table for the migration I want do undo, and then running the migration again using python manage.py migrate <migration>
.好的,我找到了一个有效的解决方案:手动删除
migrations
数据库表中的条目以进行我想要撤消的迁移,然后使用python manage.py migrate <migration>
再次运行python manage.py migrate <migration>
。
Maybe not the recommended approach but it appears to work, because the test output I added as a filler for the custom method in the migration file is displayed.也许不是推荐的方法,但它似乎有效,因为显示了我在迁移文件中作为自定义方法的填充符添加的测试输出。
Maybe the Django people could think about adding a undo_migrate
option with manage.py
.也许 Django 人可以考虑在
manage.py
添加一个undo_migrate
选项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.