How to switch the direction of a Django OneToOneField?

不打扰是莪最后的温柔 提交于 2019-11-30 21:13:37
Alasdair

First, add a OneToOneField to the child model, while keeping the original field.

class Parent(models.Model):
    parent_name = models.CharField(max_length=200)
    child = models.OneToOneField('Child', null=True, blank=True, related_name='+')

class Child(models.Model):
    child_name = models.CharField(max_length=200)
    parent = models.OneToOneField(Parent, null=True, blank=True, related_name='+')

I've set the related_name='+' so that the reverse relationships do not clash with the other field. You might find the data migration is easier if you specify a related name for one or both of the fields.

Create a migration for the new field.

Then create a data migration to populate the new field.

Finally, remove the old field, and create a new migration.

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