Django migration strategy for changing ForeignKey to IntegerField without losing data

Viewed 528

I have model

class SomeModel(models.Model):
    target_field = models.ForeignKey(
        'OtherModel', on_delete=models.PROTECT, verbose_name=_('Target Field'),
    )

And i want to change it to

class SomeModel(models.Model):
    target_field_id = models.PositiveIntegerField(_('Target field id'))

I want to do it without losing data stored in target_field_id by ForeignKey field.

I tried just to run makemigrations. But it deletes column and then creates new.

Much appreciate any help.

1 Answers

In Django ForeignKey fields store their value in an attribute with _id at the end, which you can access directly to avoid visiting the database.

I would suggest to not change the attribute name, just change target_field = models.ForeignKey to target_field = models.PositiveIntegerField. No data loss.

Related