如何处理数据库中的配方成分
Posted
技术标签:
【中文标题】如何处理数据库中的配方成分【英文标题】:How to handle recipe ingredients in database 【发布时间】:2022-01-05 13:19:00 【问题描述】:您好,我是编程新手,我正在建立一个食谱网站来学习,但我正在努力解决的是如何处理食谱成分?我想做以下事情:
拥有全球配方成分,即常见成分、鸡肉、牛肉等。 允许用户创建自己的配料(仅限该用户),即大番茄 将成分附加到配方中,无论它们是全局的还是用户创建的 允许用户将食材添加到他们的食品储藏室以及他们有多少食材库存我认为模型想要的如下,但我不确定这是正确的还是最好的方法,任何建议表示赞赏。
配方/models.py
User = settings.AUTH_USER_MODEL
class Recipe(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
recipeName = models.CharField(max_length=220) # grilled chicken pasta
userRecipeIngredients = models.ManyToManyField(UserCreatedIngredient, blank=True, Null=True, through='IngredientToRecipe')
globalRecipeIngredients = models.ManyToManyField(GlobalIngredient, blank=True, Null=True, through='IngredientToRecipe')
class UserCreatedIngredient(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
name = models.CharField(max_length=220) # grilled chicken
class GlobalIngredient(models.Model):
name = models.CharField(max_length=220) # chicken
class IngredientToRecipe(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
userIngredient = models.ForeignKey(UserCreatedIngredient, on_delete=models.SET_NULL)
globalIngredient = models.ForeignKey(GlobalIngredient, on_delete=models.SET_NULL)
quantity = models.CharField(max_length=50, blank=True, null=True) # 400
unit = models.CharField(max_length=50, blank=True, null=True) # pounds, lbs, oz ,grams, etc
instructions = models.TextField(blank=True, null=True) # chopped, diced etc.
餐具室/models.py:
from recipes.models import IngredientToRecipe
User = settings.AUTH_USER_MODEL
class pantryIngredients(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
ingredients = models.ForeignKey(IngredientToRecipe, on_delete=models.SET_NULL)
inStock = = models.IntegerField(default=0, blank=False) # user can increment i.e. two chicken in stock
【问题讨论】:
【参考方案1】:解决问题中前三个要求的一种方法是将继承构建到模型中。
class Recipe(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
recipeName = models.CharField(max_length=220) # grilled chicken pasta
ingredients = models.ManyToManyField(Ingredient, blank=True, Null=True, through='IngredientToRecipe')
class Ingredient(models.Model):
name = models.CharField(max_length=220)
class GlobalIngredient(Ingredient):
pass
class UserCreatedIngredient(Ingredient):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
class IngredientToRecipe(models.Model):
ingredient = models.ForeignKey(Ingredient, on_delete=models.SET_NULL)
quantity = models.CharField(max_length=50, blank=True, null=True) # 400
unit = models.CharField(max_length=50, blank=True, null=True) # pounds, lbs, oz ,grams, etc
instructions = models.TextField(blank=True, null=True) # chopped, diced etc.
通过允许发生这种继承,您可以改善数据冗余。
【讨论】:
以上是关于如何处理数据库中的配方成分的主要内容,如果未能解决你的问题,请参考以下文章
如何处理 SQLAlchemy、flask、python 中的唯一数据