Sultan Nasyrov
Sultan Nasyrov

Reputation: 81

Django migration strategy for changing ForeignKey to IntegerField without losing data

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.

Upvotes: 4

Views: 994

Answers (1)

Wariored
Wariored

Reputation: 1343

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.

Upvotes: 5

Related Questions