Best Django method for multiple entries for the same field

dead1999 注册会员
2023-01-24 20:58

I would create a model for Ingredient and then set a many to many ip between ingredients and recipes.

Like This:

class Ingredient(models.Model):

   name = models.CharField(max_length=150, unique=True)
   measurement_unit = models.CharField(max_length=150, unique=True)
   unit_value = models.IntegerField()
   recipe = models.ManyToManyField(Recipe)

Then from any recipe you could access all the ingredients.

dangyanshou 注册会员
2023-01-24 20:58

I don't know about the best, but the obvious one is a RecipeIngredient model.

This is a bit more complex than Scrolen's suggestion, but allows multiple recipes to use different amounts of the same ingredient. This becomes useful if there is a fair bit of information you need to attach to an ingredient. Things like supplier, sub-ingredients, allergens, nutritional info, ... you can edit the ingredient, and all the recipes that use it immediately have updated ingredient information.

class Recipe( models.Model):
    name = models.CharField( ...)
    status = models.CharField( choices = STATUS_CHOICES, ...)

class Ingredient( models.Model):
    name = models.CharField( unique=True, ...)


class RecipeIngredient( models.Model):
    recipe = models.ForeignKey( Recipe, models.PROTECT, related_name='ingredients', ...)
    ingredient = models.ForeignKey( Ingredient, models.PROTECT, ...)
    unit = models.CharField( choices=UNIT_CHOICES, ...)
    value = models.FloatField( ...)


recipe = Recipe( name = 'Lemon Cheesecake', status=Recipe.ON_HOLD )
# ON_HOLD stops anybody using a recipe only half populated with ingredients

ingredient = Ingredient.objects.get( name='lemon juice')
item = RecipeIngredient(  
    recipe = recipe,
    value=100 )

# repeat until all the ingredients are attached to the recipe
# and other stuff such as instructions are also filled in

recipe.status = Recipe.READY
# now it's ready for somebody to try to cook it!

To get the list:

recipe = Recipe.objects.get( name = 'Lemon Cheesecake')
for item in recipe.ingerdients.all():
    item.ingredient.field ... # refers to data in the related Ingredient

About the Author

Question Info

Publish Time
2023-01-24 20:58
Update Time
2023-01-24 20:58

Related Question

Error creating bean with name 'org.springframework.web.servlet.mvc.method

无法控制。net 6 WinForms应用程序的MSIX更新

Django AbstractUser ManyToManyField没有得到任何东西

JavaScript forEach循环重叠div


如何在django python中转换时间到不同的时区

Visual Studio for Mac 2022预览更改快捷键


无法更改VS Code中用于代码补全或"insertBestCompletion"的键

基于Django API Cookie或令牌的认证