Reto Reto - 16 days ago 6
Python Question

django moving a OneToOneField to a ForeignKey while keeping data

I just took over a Django project from another developer and am trying to understand what he did.

If someone could let me know if I understand correctly and point me in the right direction that would be great.

At the moment the models look like this (simplified):

class Address:
street_name=models.CharField()

class Provider:
address=models.OneToOneField(Address)

class User:
address=models.OneToOneField(Address)


But this means that each Address is unique, so no people living in the same house.

For me (coming from a Symfony framework) I would add a OneToMany field in Provider and User but in Django that is a ForeignKey in Address.

class Address:
street_name=models.CharField()
provider=models.ForeignKey(Provider)
user=models.ForeignKey(User)

class Provider:

class User:


But obviously I would like to keep the address information that is in the database.

How should I do that? Should I look into Data migration (https://docs.djangoproject.com/en/1.8/topics/migrations/#data-migrations)

Answer

If you change the OneToOneFields to ForeignKeys, then you will be able to select the same address for multiple users and providers.

class Provider:
    address=models.ForeignKey(Address)

class User:
    address=models.ForeignKey(Address)

You will need to create a migration and run it to drop the unique constraints in the database. A data migration shouldn't be required.