Search code examples
djangodjango-modelsdatabase-migrationdjango-south

Add data with Django data migration


Is it possible to add, data do DB with South data migration in Django? I don't mean change of DB structure, I need to change the value of some fields. I know that it could be done via Django admin, but I need migration way.


Solution

  • Absolutely. You need to use data migrations. With south, you can call

    $ ./manage.py datamigration <app_name> <migration_name>
    

    which will create a data migration file in your migrations module. You can then do your migration in forwards(self, orm) function. Just make sure that when accessing models, you use orm. For example, if I wanted to prefix every User's username

    def forwards(self, orm):
        for user in orm.User.objects.all():
            user.username = 'prefix' + user.username
            user.save()
    

    You can find more information in the official tutorial.