Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django South - Create Not Null ForeignKey

I have a Model

class Mystery(models.Model):
    first = models.CharField(max_length=256)
    second = models.CharField(max_length=256)
    third = models.CharField(max_length=256)
    player = models.ForeignKey(Player)

I added the player ForeignKey but when I try to migrate it using South it seems that I can't create this whith a null=False. I have this message :

The field 'Mystery.player' does not have a default specified, yet is NOT NULL. Since you are adding this field, you MUST specify a default value to use for existing rows. Would you like to:
1. Quit now, and add a default to the field in models.py
2. Specify a one-off value to use for existing columns now

I use this command :

manage.py schemamigration myapp --auto

Thanks a lot !

like image 913
MaT Avatar asked Dec 02 '22 19:12

MaT


1 Answers

This is best accomplished in 3 migrations.

Step 1. Create the new model and allow player to be null: player = models.ForeignKey(Player, null=True)

Step 2. Run ./manage.py schemamigration <app> --auto

Step 3. Run ./manage.py datamigration <app> set_default_players

Step 4. Update forwards and backwards in <app>/migrations/<number>_set_default_players.py to use whatever logic you like for setting the default player. Ensure that every Mystery object has a value for player.

Step 5. Update the Mystery model so that player has null=False.

Step 6. Run ./manage.py schemamigration <app> --auto

Step 7. Run ./manage.py migrate <app>

like image 144
Josh Avatar answered Dec 31 '22 11:12

Josh