How to add one to one relation field in a existing model through South migration

十年热恋 提交于 2020-01-12 18:37:02

问题


I already have a model,

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

and i have many entries in it. Now i want to add a field in it, which is

user = models.OneToOneField( User )

How do i add this field into ModelA? Is there any solution other than deleting all previous entries?


回答1:


I would use this pattern:

  1. Add "user = models.OneToOneField(User, null=True)" to your Model (don't remove the "name" field)
  2. run 'manage.py schemamigration --auto'. And apply the migration. Now there are two columns in your table.
  3. Now create a datamigration. Edit the file: you need to loop over all objects in your model and set the user field.
  4. Remove the "name=models.CharField" from the model.py file. And remove the null=True from the user field.
  5. run 'manage.py schemamigration --auto'. And apply the migration

BTW, if you use OneToOneField() without null=True, you can set primary_key=True on this field, since it must be unique. But I don't know if south can handle this migration.



来源:https://stackoverflow.com/questions/8586703/how-to-add-one-to-one-relation-field-in-a-existing-model-through-south-migration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!