django - write an advanced migration with south -


i added field "is_capital" model "realm" has foreign key pointing "user".

this looks like:

class realm(models.model):     user = models.foreignkey(user)     is_capital = models.booleanfield( default=false ) #field not synced yet     #... 

by default, want records per user have "is_capital" flag set false, first (or random one). in end there should 1 "realm" flagged "is_capital" per user.

so table should in end:

realm

realm_id ; user_id ; is_capital 1 ; 1 ; true 2 ; 1 ; false 3 ; 1 ; false 4 ; 2 ; true 5 ; 2 ; false 

how can such migration ? examples have seen filling new columns single value.

add schemamigration add field default=false.

python manage.py schemamigration app_name --auto 

run migration.

then create data migration making changes

./manage.py datamigration app_name mark_is_capital 

in forwards() of created migration file, write:

for user in orm.user.objects.all():     realms = orm.realm.objects.filter(user=user)     if realms:         realm_to_change = realms[0]         realm_to_change.is_capital = true         realm_to_change.save() 

Comments

Popular posts from this blog

javascript - Count length of each class -

What design pattern is this code in Javascript? -

hadoop - Restrict secondarynamenode to be installed and run on any other node in the cluster -