0

I am working on an unguided project and I have been trying to create an instance of RecipeRequirements model but I get;

ValueError: Cannot assign "1": "RecipeRequirements.ingredient" must be a "Ingredient" instance.

These are the instances I want to create and I did create Ingredient instances without any error.

enter image description here

I think I am missing something with related to foreignkey, I thought 'unique=True' would create id for each instances in the Ingredient name field, so I wouldn't have to add another _id field.

I get the error after running this;

recipe_requirements_1 = RecipeRequirements(ingredient=1, quantity=100.0, menu_item=1)

Here is my models.py

from django.db import models

class Ingredient(models.Model):
    name = models.CharField(max_length=200, unique=True)
    quantity = models.FloatField(default=0)
    unit = models.CharField(max_length=200, default="tbsp")
    price_per_unit = models.FloatField(default=0.00)

class MenuItem(models.Model):
    title = models.CharField(max_length=200, unique=True)
    menu_price = models.FloatField(default=0.00)

class RecipeRequirements(models.Model):
    ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE)
    quantity = models.FloatField(default=0.00)
    menu_item = models.ForeignKey(MenuItem, on_delete=models.CASCADE)


class Purchase(models.Model):
    menu_item = models.ForeignKey(MenuItem, on_delete=models.CASCADE, null=True)
    timestamp = models.DateTimeField(auto_now_add=True, null=True)
 
  • If you want to pass the `id` of an instance, then you have to do it with `ingredient_id = 1`. Otherwise you have to pass the `Ingredient` object itself. The same error will arise for `menu_item`. – solarissmoke Apr 19 '22 at 06:33
  • thank you @solarissmoke I wasn't aware of the "_id" in django. – bloodymoonmate Apr 19 '22 at 07:41

0 Answers0