Django South - Create Not Null ForeignKey

前端 未结 3 1593
抹茶落季
抹茶落季 2021-02-06 16:09

I have a Model

class Mystery(models.Model):
    first = models.CharField(max_length=256)
    second = models.CharField(max_length=256)
    third = models.CharFie         


        
3条回答
  •  后悔当初
    2021-02-06 16:40

    Another option is to create a data migration before adding the ForeignKey, in which you create a new Player instance with a specific id. Be sure that that id does not exist previously in your database.

    1.Create the data migration file

    $ ./manage.py datamigration myapp add_player
    Created 00XX_add_player.py
    

    2.Edit the forwards and backwards methods of the file:

    def forwards(self, orm):
        orm['myapp.Player'].objects.create(name=u'Very misterious player', id=34)
    
    def backwards(self, orm):
        # Haven't tested this one yet
        orm['myapp.Player'].objects.filter(id=34).delete()
    

    3.Add the ForeignKey to your Mistery class and migrate the schema again. It will ask for the default value to your data migration id, in this example, 34.

     $ ./manage.py schemamigration --auto myapp
     ? The field 'Mistery.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
     ? Please select a choice: 2
     ? Please enter Python code for your one-off default value.
     ? The datetime module is available, so you can do e.g. datetime.date.today()
     >>> 34
     + Added field player on myapp.Mistery
    Created 0010_auto__add_field_mistery_player.py. You can now apply this migration with: ./manage.py migrate myapp
    

    4.Finally run the migrate command and it will execute the migrations in sequential order, inserting the new Player and updating all the Mistery rows with the reference to your new Player.

提交回复
热议问题