简体   繁体   中英

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

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. 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?

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:

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> .

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM