Home > OS >  Why is Django giving me a ValueError when I reference a class within the same model?
Why is Django giving me a ValueError when I reference a class within the same model?

Time:12-03

I'm building a simple recipe app, and so far I have two models: Ingredient and Recipe.

Each recipe should have multiple ingredients, so I laid out my model like this:

class Ingredient(models.Model):
    name = models.CharField(max_length=50)

class Recipe(models.Model):
    title = models.CharField(max_length=100)
    ingredients = models.ForeignKey(Ingredient, on_delete=CASCADE)
    instructions = JSONField()
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=SET_DEFAULT, default='Chef Anon')

When I makemigrations, I get nothing, but when I migrate, I get this ValueError:

ValueError: Cannot alter field cookbook.Recipe.ingredients into cookbook.Recipe.ingredients - they do not properly define db_type (are you using a badly-written custom field?)

Following the example here (Django: Add foreign key in same model but different class), I've tried setting ingredients=models.ForeignKey(Ingredient, on_delete=CASCADE) as well as using lazy syntax ingredients=models.ForeignKey("Ingredient", on_delete=CASCADE), but each time, makemigrations shows no changes, and migrate gives me the same ValueError.

Edit My imports:

from django.db.models.deletion import CASCADE, SET_DEFAULT, SET_NULL
from django.db.models.fields.json import JSONField
from django.utils import timezone
from django.contrib.auth.models import User```

CodePudding user response:

Try replacing on_delete=CASCADE with on_delete=models.CASCADE

If you have not imported CASCADE separately from models.

All though, in that case you should get a warning that "CASCADE is not defined".

CodePudding user response:

I believe I found the problem: My models.py file was in the root directory, not in the app directory.

  • Related