How to add one or one relationship field to an existing model through southern migration

I already have a model,

class ModelA( models.Model ): name = models.CharField ( max_length = 255, blank = False ) 

and I have a lot of entries. Now I want to add a field to it that

 user = models.OneToOneField( User ) 

How to add this field to ModelA ? Is there any solution besides deleting all previous entries?

+6
source share
1 answer

I would use this template:

  • Add "user = models.OneToOneField (User, null = True)" to your model (do not delete the "name" field)
  • run 'manage.py schemamigration -auto'. And apply the migration. Your table now has two columns.
  • Now create a datamigration. Edit the file: you need to iterate over all the objects in your model and set the user field.
  • Remove "name = models.CharField" from the model.py file. And remove the null = True value from the user field.
  • run 'manage.py schemamigration -auto'. And apply the migration

By the way, if you use OneToOneField () without null = True, you can set primary_key = True in this field, since it must be unique. But I do not know if the south will be able to cope with this migration.

+11
source

Source: https://habr.com/ru/post/904219/


All Articles