0

Another follow up question to Creating a Django Model for a recipe #2.

I've run into an error with the following code:

class Ingredient(models.Model):
    '''All ingredients for any recipe or individual selection'''
    name = models.CharField(max_length=50)
    department = models.ForeignKey(Department, null=True, on_delete=models.SET_NULL)
    
    def __str__(self):
        return self.ingredient
    
class IngredientDetail(models.Model):
    '''A class to identify variable quantities of ingredients'''
    ingredient = models.ForeignKey(Ingredient, null=True, on_delete=models.SET_NULL)
    quantity = models.CharField(max_length=1)
    
    class Meta:
        verbose_name_plural = 'Ingredient Details'
    
    def __str__(self):
        return self.quantity
    
class Recipe(models.Model):
    '''A Recipe class to input new recipes'''
    recipe = models.CharField(max_length=50)
    ingredients = models.ManyToManyField(Ingredient, through=IngredientDetail)
    instructions = models.TextField(null=True)
    cuisine = models.ForeignKey(Cuisine, null=True, on_delete=models.SET_NULL)
    picture = models.ImageField(upload_to= 'media/', null=True, blank=True)

    def __str__(self):
        return self.recipe

I've set it up this way to associate variable quantities of ingredients with multiple recipes. However, when I run this code, the following issue is identified by Django:

grocery_lists.IngredientDetail: (fields.E336) The model is used as an intermediate model by 'grocery_lists.Recipe.ingredients', but it does not have a foreign key to 'Recipe' or 'Ingredient'.

As you can see, there IS a foreign key to 'Ingredient', so I'm not sure whats wrong.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
  • 3
    It needs a foreign key to **both** `Ingredient` and `Recipe` because it needs to be used as a through model. – Abdul Aziz Barkat May 13 '22 at 14:43
  • Also one piece of feedback, the question's title is not great. The title should summarize your question, the title of this question isn't related to the problem you face at all. – Abdul Aziz Barkat May 13 '22 at 15:27
  • @AbdulAzizBarkat Thank you, i will try to refactor the models, but I can already see an issue. If the models reference each other with foreign keys, won’t there be an ‘undefined’ error since one of the classes is after the one referencing it? – HoundDogSaw May 13 '22 at 16:12
  • 1
    The Django developers have already thought of that :) You can use a lazy reference i.e. you can simply specify the name of the other model as a string. See the [docs](https://docs.djangoproject.com/en/4.0/ref/models/fields/#foreignkey). Also see this question: https://stackoverflow.com/questions/3682513/django-models-py-circular-foreign-key – Abdul Aziz Barkat May 13 '22 at 16:16
  • Every time I turn a corner with this stuff, I'm smacked in the face by the reality that there's people that are light-years ahead of me. It's incredible. – HoundDogSaw May 13 '22 at 19:25

0 Answers0