'Unable to update/delete item from table even with on_delete=CASCADE

I am trying to make a Cooking Recipe Portal DB and none of the DELETE queries work for me.

Here are my tables/models related to the error:

class Ingredient(models.Model):
    ingredientid = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=255)
    type = models.CharField(max_length=255)

class IngredientRecipe(models.Model):
    ingredientid = models.ForeignKey("Ingredient", to_field="ingredientid", on_delete=models.SET_NULL, null=True)
    recipeid = models.ForeignKey("Recipe", to_field="recipeid", on_delete=models.SET_NULL, null=True)
    amount = models.CharField(max_length=255)

    class Meta:
        unique_together = ("ingredientid", "recipeid")

class IngredientNutrition(models.Model):
    nutritionid = models.IntegerField(null=True, blank=True)
    ingredientid = models.ForeignKey("Ingredient", to_field="ingredientid", on_delete=models.CASCADE)
    #ingredientid = models.OneToOneField(Ingredient, on_delete=models.CASCADE)
    portionsize = models.FloatField(max_length=24)
    calories = models.IntegerField()
    fat = models.IntegerField()
    protein = models.IntegerField()
    sodium = models.IntegerField()
    carbs = models.IntegerField()

    class Meta:
        unique_together = (("nutritionid", "ingredientid"), )

Table Schemas:

Ingredient Table Ingredient Table

IngredientRecipe Table IngredientRecipe Table

IngredientNutrition Table IngredientNutrition Table

Issue: Say i want to delete ingredient.ingredientID = 20 or ingredient.name = 'Corn Starch', it won't let me delete because ingredientID = 20 is still referenced by the table IngredientNutrition.

Code I tried: DELETE FROM recipeportaldb_ingredient WHERE recipeportaldb_ingreident.ingredientid = 20;

Error message: Key (ingredientid)=(20) is still referenced from table "recipeportaldb_ingredientnutrition" If I try other ingredientid values, error changes to ... from table "recipeportaldb_ingredientrecipe"

I tried altering the parameters inside the models.ForeignKey and changed parameters in various keys in different tables to see if it allowed me to delete.



Solution 1:[1]

First, you have to delete the IngredientNutrition object that refers to the Ingredient object you want to delete, then you can delete the Ingredient obj

DELETE FROM recipeportaldb_IngredientNutrition 
WHERE ingredientid = 20;

Then...

DELETE FROM recipeportaldb_ingredient 
WHERE ingredientid = 20;

If you are using django to handle this, it can be done with single line:

Ingredient.objects.get(ingredientid=20).delete()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Adil Mohak