I have a class like this :
class someClass1(models.Model):
# some field 1
custom_vhd_azure_tbl = models.ForeignKey(Vhd_azure, on_delete=models.CASCADE)
# some field n
created_date = models.DateTimeField(auto_now_add=False, null=True)
I now realize a mistake was made : custom_vhd_azure_tbl should’ve been FKed to Custom_vhd_azure instead.
custom_vhd_azure_tbl = models.ForeignKey(Custom_vhd_azure, on_delete=models.CASCADE)
Some 10 rows of data currently exits in someClass1 table for which it can be truncated.
But what I should do to make the field switch from one FK to another ?
Does the Custom_vhd_azure
model has any fk to Vhd_azure
so you could relate one from the other?
If there’s no relation, then you wont be able to keep the data on these rows
Custom_vhd_azure
and Vhd_azure
are 2 separate distinct tables that have no FKs.
Then you have no way of keeping this existing data.
What you can do, if you have a way to, is:
- Remove the field
custom_vhd_azure_tbl
from the model, run makemigrations
. It will generate a RemoveField operation
- Add the field
custom_vhd_azure_tbl
in the model for the correct model, run makemigrations
. It will generate a AddField operation
- Run
makemigrations your_app --empty
to generate a empty migration, that you can use to write a RunPython
operation to populate the existing rows with the proper model for that foreign key.
Following these steps you can “keep” the field custom_vhd_azure_tbl
with the new values.
How do I execute RunPython
post empty makemigrations ?
You can find all possible migration operations under this section of the documentation: Migration Operations
And there you can find about RunPython