3

I have a model with a foreign key field. I want to remove the foreign key reference. However, migration fails because of the following error:

Cannot delete or update a parent row: a foreign key constraint fails

I understand what is going on, but I don't know how to resolve this properly with Django. Right now (since I'm at the beginning of my project), I go into the MySQL database manually and delete the tables and re-migrate as if it was the first migration.

Is there a way, using Django, to get around this foreign key constraint issue?


I'm using Django 1.7
Database backend is MySQL

EDIT - Models Before/After migrations

Before:

class Skills(models.Model):
  # fields here...

class Project(models.Model):
  skills = models.ForeignKey(Skills, verbose_name = "Required Skills", blank = True, null = True)

After:

class Skill(models.Model):
  # fields here...

class Project(models.Model):
  skills = models.ForeignKey(Skill, verbose_name = "Required Skills", blank = True, null = True)

I'm pretty sure all I've done is removed the "Plural" from the Skill model. The the makemigrations command works fine, but the migrate command fails with the above noted error.


EDIT 2

Hit the same error:

Cannot drop column 'skills_id': needed in a foreign key constraint 'projects_project_skills_id_4cc7e00883ac4de2_fk_projects_skill_id'

This time I dropped the field skill from model Project

1
  • This is an error you can expect when you are deleting or updating a row; not when you are changing database schema. Can you post your models (before and after migration)? Commented Mar 22, 2015 at 15:05

2 Answers 2

1

A little hack I used:

  • Add a migration operations that first alters the field to say IntegerField before other operations i.e

operations = [ migrations.AlterField( model_name='projects_project', name='skills', field=models.IntegerField(default=0) ), ..... other migration entries now after this. ]

Sign up to request clarification or add additional context in comments.

1 Comment

Your hack worked for me. I had this same issue adding a ForeignKey column. I used migrations.AddField(...UUIDField...) first for the field then put the AlterField after.
0

This is my SOLUTION (do this manually first)

ALTER TABLE forms_formentry DROP FOREIGN KEY forms_formentry_form_id_d0f23912_fk_forms_form_page_ptr_id

This is the ERROR

django.db.utils.OperationalError: (1833, "Cannot change column 'page_ptr_id': used in a foreign key constraint 'forms_formentry_form_id_d0f23912_fk_forms_form_page_ptr_id' of table 'dbname.forms_formentry'")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.