JM Lontoc
JM Lontoc

Reputation: 221

OperationalErrors - no such column django - ForeignKey

I have this field in my model:

customer = models.ManyToManyField(Customer)

Due to some changes, I realized that I have to change the relationship to this:

customer = models.ForeignKey(Customer)

I have tried to do the makemigrations app_name and migrate again and again but it still produces the error. I also have tried deleting the existing data of the model in the admin site.

Upvotes: 1

Views: 558

Answers (1)

hynekcer
hynekcer

Reputation: 15548

A simple change from ManyToManyField to ForeignKey is not possible without data loss. Problems with migrations can be solved by splitting an impossible migration to smaller migrations. e.g. if data are important

A) with data loss:

  • delete ManyToManyField
  • makemigrations
  • add ForeignKey
  • makemigrations

B) with partial data loss, that only first element of ManyToManyField will be converted for every object to ForeignKey:
Add ForeignKey with other name, makemigrations, makemigrations --empty, edit it to Data Migration to copy the column data, remove ManyToManyField; makemigrations, makemigrations --empty, edit it to rename the field.

Upvotes: 1

Related Questions