0

I need a help regarding django.db.utils.IntegrityError: I read similar questions on stackoverflow before posting a new question, but I could not find the right solution.

Basically, I am following a course, let's say copy-pasting the code in models.py, serializers.py views.py And whenever I call python manage.py migrate, I get this error:

django.db.utils.IntegrityError: The row in table 'LittleLemonAPI_menuitem' with primary key '1' has an invalid foreign key: LittleLemonAPI_menuitem.category_id contains a value '1' that does not have a corresponding value in LittleLemonAPI_category.id.

Anyone can help, how could I fix that error? The strange part is, that I literally follow each step on the course, it isn't even my code, and I can't figure out what's wrong.

I tried to delete all migration related files and db.sqlite3, but in that way I lose all the previously entered data.

I tried changing the part from on_delete.PROTECT, default=1. into. on_delete.CASCADE and removing default1, but nothing worked.

2 Answers2

0

It's basically complaining about not finding a "LittleLemonAPI_category" with id of "1" here:

'1' that does not have a corresponding value in LittleLemonAPI_category.id.

You need to insert a category with the id of 1 before inserting your menuitem

sergenp
  • 510
  • 4
  • 13
0

The easiest way to solve this error, Comment out the Category class and Foreign Key from MenuItem class like this: example with image

from django.db import models

#class Category(models.Model):
#   slug = models.SlugField()
#   title = models.CharField(max_length=255)

class MenuItem(models.Model):
    title = models.CharField(max_length=255)
    price = models.DecimalField(max_digits=6, decimal_places=2)
    inventory = models.SmallIntegerField()
    # category = models.ForeignKey(Category, on_delete=models.PROTECT, default=1)

Then remove the 'category' from serializers field. After that, run the server and go to the single menu item from your browser. You can find your single item like that: http://127.0.0.1:8000/api/menu-items/2

Delete these items one by one and then remove the class comment, migrate and run again your server. Hope it will work.

Shohan
  • 92
  • 1
  • 1
  • 6
  • You should use code blocks instead of screenshots, so the other users don't have to open the link, and so they can copy-paste your solution. – ThomasGth Mar 17 '23 at 10:45