Django 1.8: Delete/rename a model field in data migration
You just need to create two additional migrations: one to remove the old field and the other to alter the new field.
First remove dealbase.categoria and create a migration and then rename dealbase.categoria-tmp to dealbase.categoria and create another migration.
This will delete the first field and then alter the tmp field to the correct name.
user123892
Updated on June 05, 2022Comments
-
user123892 almost 2 years
I need to change the relationship of a model field from ForeignKey to ManyToManyField. This comes with a data migration, to update the pre-existing data.
The following is the original model (models.py):
class DealBase(models.Model): [...] categoria = models.ForeignKey('Categoria') [...] )
I need the model field 'categoria' to establish a many2many relationship with the model 'Categoria' in the app 'deal'.
What I did:
Create a new field 'categoria_tmp' in DealBase
class DealBase(models.Model): categoria = models.ForeignKey('Categoria') categoria_tmp = models.ManyToManyField('Categoria',related_name='categoria-temp')
make a schema migration
python manage.py makemigrations
Edit the migrationfile.py to migrate data from categoria to categoria-tmp
def copy_deal_to_dealtmp(apps, schema_editor): DealBase = apps.get_model('deal', 'DealBase') for deal in DealBase.objects.all(): deal.categoria_tmp.add(deal.categoria) deal.save() class Migration(migrations.Migration): dependencies = [ ('deal', '0017_dealbase_indirizzo'), ] operations = [ migrations.AddField( model_name='dealbase', name='categoria_tmp', field=models.ManyToManyField(related_name='categoria-temp', to='deal.Categoria'), preserve_default=True, ), migrations.RunPython( copy_deal_to_dealtmp ) ]
make data migration
python manage.py migrate
Finally I need to delete the column 'dealbase.categoria' and rename the column 'dealbase.categoria-tmp' to 'dealbase.categoria'
I'm stuck at step 5.
Could someone help me out? I cannot find online an answer, I'm using Django 1.8.
Thanks!
-
user123892 almost 9 yearsThank you for your answer. I did as Jeff_Hd suggested and it worked. I'm sure your solution is also a valid one. If @Jeff_Hd does not make an answer from his comment, I will give the 'solved' to yours.
-
itzMEonTV almost 9 yearsNo, please accept the answer which solved your problem. I am not at all sure this is best answer.If Jeff_Hd's answer solved yours, accept it.
-
bruno desthuilliers over 6 yearsFor anyone reading ths answer : steps 2 and 5 are plain wrong, you want data migrations instead.
-
Sido4odus almost 3 yearsDoes Django execute operations in order (sequentially) ?