I'm quite new in Django and in this project I need to manage information about a restaurant. The problem is that I can't add more than one ingredient required to a recipe
My models.py is this:
from django.db import models
# Create your models here.
class Ingredient(models.Model):
name = models.CharField(max_length=35)
quantity = models.IntegerField()
unit = models.CharField(max_length=5)
unit_price = models.FloatField()
def __str__(self):
return self.name
class MenuItem(models.Model):
title = models.CharField(max_length=35)
price = models.FloatField()
example = models.ImageField()
def __str__(self):
return self.title
class RecipeRequirement(models.Model):
menu_items = models.ForeignKey(MenuItem, default = 1, on_delete=models.SET_DEFAULT)
ingredient = models.CharField(max_length=35)
quantity = models.FloatField()
def __str__(self):
return str(self.menu_items)
class Purchase(models.Model):
menu_item = models.ForeignKey(MenuItem, default=1, on_delete=models.SET_DEFAULT)
timestamp = models.DateTimeField()
def __str__(self):
return 'Purchase ' str(self.menu_item) str(self.timestamp)
After replacing "ingredients = models.CharField()" for "ingredients = models.ManyToManyField()" a list of all ingredients appear:
[![enter image description here][2]][2]
But when I add a new ingredient to my Ingredient model, it automatically appears in every single menu_item:[![enter image description here][3]][3]
CodePudding user response:
You need to have a ManyToMany relationship in your RecipeRequirement model. This will allow you to select multiple ingredients for any one RecipeRequirement object. Read more here: Django ManyToMany Fields
class RecipeRequirement(models.Model):
menu_items = models.ForeignKey(MenuItem, default = 1, on_delete=models.SET_DEFAULT)
ingredients = models.ManyToManyField(Ingredient)
quantity = models.FloatField()
def __str__(self):
return str(self.menu_items)
CodePudding user response:
Set ingredients in the RecipeRequirement class as a ManyToMany field on the Ingredient class:
class RecipeRequirement(models.Model):
menu_items = models.ForeignKey(MenuItem, default = 1, on_delete=models.SET_DEFAULT)
ingredients = models.ManyToManyField(Ingredient)
quantity = models.FloatField()
def __str__(self):
return str(self.menu_items)
CodePudding user response:
I believe that your Ingredient
class must have a ForeignKey
associated with the RecipeRequirement
in order to add more than one ingredient related to the recipe.
I suggest using a website like https://drawsql.app/ in order to obtain a better visualization of your database relationships.