I am new to Django and I am stuck on an error "Foreign key mismatch error" while migrating my project. I have the following models in my project:
from django.db import models
# Create your models here.
class Product(models.Model):
product_id=models.AutoField
product_name=models.CharField(max_length=50)
product_desc=models.CharField(max_length=50)
product_date=models.DateField()
product_image=models.ImageField(upload_to="shop/images",default="")
def __str__(self):
return self.product_name
class User(models.Model):
user_email=models.EmailField(primary_key=True)
user_name=models.CharField(max_length=20)
def __str__(self):
return self.user_email
class Student(models.Model):
course=(
('MS','MS'),
('BS','BS')
)
student_name=models.CharField(max_length=40)
student_roll=models.IntegerField(primary_key=True)
student_course=models.CharField(max_length=100,choices=course)
class Order(models.Model):
user=models.ForeignKey(Student, on_delete=models.CASCADE)
id=models.IntegerField(primary_key=True)
date=models.DateField()
time=models.TimeField()
price=models.FloatField()
def __str__(self):
return str(self.id)
class Teacher(models.Model):
user_email=models.EmailField(primary_key=True)
user_name=models.CharField(max_length=20)
def __str__(self):
return self.user_email
I also created two more tables; Person and Group but I deleted these two tables later. Now, when I migrate my project using python manage.py makemigrations and then python manage.py migrate
I still get the error;
django.db.utils.OperationalError: foreign key mismatch - "shop_membership" referencing "shop_person"
So, what should I do now?
You should still have the migration file in which you have the Person and Group models. So you should delete the migration file that contains these models, but before deleting them be sure to revert the migrations if you have previously applied them.
To revert a migration, you can run:
python manage.py migrate app_name xxxx_migration_before_the_one_you_want_to_un_apply
If you just started with the project, you can also revert all existing migrations by running:
python manage.py migrate app_name -- zero
This will revert all the applied migrations after which you can simply delete all the migration files and then re-run makemigrations and migrate commands to create all migrations in a single file and apply them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With