paldepind
paldepind

Reputation: 4870

How to create new field in a model with initial data from another field?

In my Django app I have a model like the following:

class Foo(models.Model):
  ...
  user = models.OneToOneField(User)
  ...

Here user is from django.contrib.auth.models. I'm using South for migrations and I want to extend Foo with a new boolean field with the initial data equal to the is_active field in in the User model contained in Foo's user field.

Upvotes: 0

Views: 81

Answers (1)

falsetru
falsetru

Reputation: 369124

Use Data migrations

  1. Do a schema migration first: add is_active field to Foo class.

    # edit your appnames/models.py
    python manage.py schemamigration appname --auto 
    python manage.py migrate appname
    
  2. Do a data migration:

    $ python manage.py datamigration appname copy_is_active
    
  3. Edit appname/migrations/0???_copy_is_active.py, especially forwards method to do what you want.

    For example,

    ....
    from appname.models import Foo
    
    class Migration(DataMigration):
        def forwards(self, orm):
            for obj in Foo.objects.all():
                obj.is_active = obj.user.is_active
                obj.save()
            #for yn in (True, False):
            #    Foo.objects.filter(user__is_active=yn).update(is_active=yn)
    ...
    
  4. Execute the migration

    $ python manage.py migrate appname
    

Upvotes: 2

Related Questions