将需要链接的数据插入SQL数据库

2024-04-28 22:25:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我不确定这个问题的确切措辞是什么,所以如果我找不到任何资源来告诉我怎么做,那很可能就是原因

基本问题是,我有一个用Python编码的webcrawler,它有一个“Recipe”对象,该对象存储有关特定配方的某些数据,例如“Name”、“Instructions”、“contracents”等,其中“Instructions”和“contracents”是一个字符串数组

现在,当我想将这些数据存储在数据库中以便从其他来源访问时,我遇到了一个问题

数据库的基本示例如下所示:

(食谱) 身份证,姓名

(配料) 身份证,姓名

(接收元件) 身份证,身份证

现在,特别是我的问题是,如何确保我没有复制配料,如何插入数据,以便配料链接到当前配方对象的id

我知道我的解释不好,但我正努力用语言表达出来。谢谢您的帮助


Tags: 数据对象数据库编码配方recipe原因资源
2条回答

对于第一个问题(我如何确保我没有复制配料?),如果我理解的很好,基本上是把你的主键作为(I\u id,name)放在配料表中。这样您就可以保证不可能插入具有相同密钥(i\u id,name)的成分

现在是第二个问题(如何插入数据以便将配料链接到当前配方对象的id?)。我真的不太明白这个问题。我想你想要的是把食谱和配料联系起来。这可以通过RecipeIngElements表来实现。当您想这样做时,只需在该表中插入一个新行,其中包含配方id和配料id。如果这不是你想要的对不起,但我真的不明白

对于第一个问题,我认为您缺乏数据处理和数据库设计经验。但别担心,它可以通过实践来学习

关于第二个问题,让我们开门见山。 食谱和数据库中的配料是相关的,但实际上每个食谱的配料都是不同的,配料包括许多食物元素鸡蛋、肉、面粉等。 创建RecipeIngElements表时,不能显示其中一个配方使用了这些成分。收件人的id应存储多种成分 不是一种成分。它需要修理

我建议RecipeIngElements表设置r\u id(OneToOneField)和I\u id(textfield)列。如果您是用django编程,那么注释是model字段

我假设你的模型是这样的:

# Recipes model
class Recipes(models.Model):
    r_id = models.IntegerField(primary_key=True)
    name = models.TextField()

# Ingredients model
class Ingredients(models.Model):
    i_id = models.IntegerField(primary_key=True)
    name = models.TextField()

# RecipeIngredients model
class RecipeIngredients(models.Model):
    r_id = models.OneToOneField(Ingredients, primary_key=True)
    i_ids = models.TextField()

下道工序数据:

# fake data
the_recipe =  "Pasta Sauce with Meatballs"
the_ingredients = ["Pasta Sauce", "meatballs", "spaghetti"]

# save the recipe in database
recipe_object = Recipes(name="the_recipe").save()

# save the ingredients in database
i_ids_arrary = []
for i in the_ingredients:
    ingredient_object = Ingredients(name=i).save()
    i_ids_arrary.append(str(ingredient_object.i_id))
i_ids_string = ",".join(i_ids_arrary)

# save RecipeIngredients
RecipeIngredients(r_id=recipe_object, i_ids=i_ids_string).save()

我认为它可以详细地完成大部分任务。希望你能参考一下

相关问题 更多 >