Atma
Atma

Reputation: 29767

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?

Upvotes: 4

Views: 1585

Answers (2)

alecxe
alecxe

Reputation: 473873

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')

Upvotes: 1

Rohan
Rohan

Reputation: 53326

You can add your code in migration script created by south.

If you have updated a model and done schemamigration with south, it will create a script to apply that migration. It will be in appname/migration/00N_some_name.py.

You can add your code in forwards() method in that script at the end after schema alteration is done.

Upvotes: 0

Related Questions