Search code examples
mysqldjangodjango-modelsdjango-south

how to populate database fields when model changes in django


I have a django app that is evolving. The model often changes and I use Django South to apply schema migrations.

Sometimes my changes involve populating new values that are added based on sql logic.

For example, added a new boolean flag for currently paying users. I have added the field, applied the migration but now I want to populate the field based on the data from other table to show who is paying.

I know I can do this with a simple sql statement, but my environment is automated and uses CI. I want to push changes and have the flag populated automatically.

How can I accomplish this? With South? With Django?


Solution

  • There is a thing called data migration, this is a perfect use case for it:

    Data migrations are used to change the data stored in your database to match a new schema, or feature.

    from south.v2 import DataMigration
    from django.conf import settings
    
    class Migration(DataMigration):
        def forwards(self, orm):
            # update your user's boolean flag here
    

    See an example of a data migration here.

    Or, alternatively, you can open your schema migration .py file and populate your field in forwards() method, like this:

    class Migration(SchemaMigration):
        def forwards(self, orm):
            # Adding field 'User.paying'
            db.add_column(u'user', 'paying',
                          self.gf('django.db.models.fields.BooleanField')(default=True),
                          keep_default=False)
    
            # update your user's boolean flag here
    
        def backwards(self, orm):
            # Deleting field 'User.paying'
            db.delete_column(u'user', 'paying')