[Django]-How to populate database fields when model changes in django

1👍

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

0👍

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.

👤Rohan

Leave a comment