如何通过南方迁移在现有的模型中添加一对一的关系字段 [英] How to add one to one relation field in a existing model through South migration

查看:103
本文介绍了如何通过南方迁移在现有的模型中添加一对一的关系字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经有一个模型,

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 )

如何将此字段添加到 ModelA ?除了删除所有以前的条目之外,是否有其他解决方案?

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

推荐答案

我会使用这种模式:


  1. 将user = models.OneToOneField(User,null = True)添加到您的模型中(不要删除name字段)

  2. 运行'manage.py schemamigration --auto'。并应用迁移。现在表中有两列。

  3. 现在创建一个数据迁移。编辑文件:您需要循环使用模型中的所有对象并设置用户字段。

  4. 从model.py文件中删除name = models.CharField。并从用户字段中删除null = True。

  5. 运行'manage.py schemamigration --auto'。并且应用迁移

  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,如果您使用OneToOneField()而不使用null = True,则可以在此字段上设置primary_key = True,因为它必须是唯一的。但是我不知道南方是否可以处理这种迁移。

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.

这篇关于如何通过南方迁移在现有的模型中添加一对一的关系字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆