【问题标题】:How make list of ingredients in recipes in SQLITE3 Python如何在 SQLITE3 Python 中制作食谱中的成分列表
【发布时间】:2021-12-11 20:24:59
【问题描述】:

我正在尝试制作食谱数据库。在带有 col“成分”的“食谱”表中,我想要一个成分 ID 列表,例如[2,5,7]。我可以做这样的事情还是我应该寻找其他解决方案?

import sqlite3

conn = sqlite3.connect('recipes.db')
c = conn.cursor()


c.execute('''CREATE TABLE recipes(ID INT, name TEXT, ingredients INT)''')
c.execute('''CREATE TABLE ingredients(ID INT, nazwa TEXT, kcal REAL)''')

另一个想法是制作另一张表(配料表),我将在其中有 15 列的配料数量。

c.execute('''CREATE TABLE The_list_of_ingredients(ID INT, ingredient1   INT,    ingredient2 INT,    ...)''')

我可以将每种成分 1、成分 2 ... 与它们各自的成分 ID 联系起来吗?

【问题讨论】:

  • 每种成分最多可以属于1个配方还是每种成分可以属于多个配方?

标签: python sql sqlite


【解决方案1】:

您可能会在食谱及其成分之间寻找a many-to-many relation

CREATE TABLE recipes(ID INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE ingredients(ID INTEGER PRIMARY KEY, name TEXT, kcal REAL);
CREATE TABLE recipe_ingredients(
  ID INTEGER PRIMARY KEY AUTOINCREMENT,
  recipe_id INTEGER,
  ingredient_id INTEGER,
  quantity REAL,
  FOREIGN KEY(recipe_id) REFERENCES recipes(ID),
  FOREIGN KEY(ingredient_id) REFERENCES ingredients(ID)
);

这样你的数据可能看起来像例如

成分

id name kcal
1 egg 155
2 cream 196

食谱

id name
1000 omelette

recipe_ingredients

recipe_id ingredient_id quantity
1000 1 100
1000 2 50

(假设kcal 是每 100 克的千卡,quantity 是克和一个相当奶油的煎蛋卷)

【讨论】:

    【解决方案2】:

    您可以尝试将 id 存储为字符串

    json.dumps(list_of_ingredients_ids)
    

    但可能最好的解决方案是多对多关系

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-29
      • 1970-01-01
      相关资源
      最近更新 更多