首页 > 解决方案 > 从烧瓶形式的 JSON 数据中删除多个项目

问题描述

我有一个 WTForm 以 JSON 格式提交其数据。假设数据库是许多配方步骤的一种配方。

{
  "stepset-0": {
    "recipe_step_id": "5", 
    "recipe_step_name": "step 1", 
    "recipe_step_temp": "666.0"
  }, 
  "stepset-1": {
    "recipe_step_id": "6", 
    "recipe_step_name": "Step 2", 
    "recipe_step_temp": "57.0"
  }, 
  "stepset-2": {
    "recipe_step_id": "7", 
    "recipe_step_name": "Step 3", 
    "recipe_step_temp": "68.0"
  }, 
  "stepset-3": {
    "recipe_step_id": "8", 
    "recipe_step_name": "Step 4", 
    "recipe_step_temp": "73.0"
  }
}

我正在使用 JS 从表中删除元素,但目前正试图了解如何更新recipe_steps表中的数据。

逻辑基本上应该是:

  1. 在步骤表中找到与配方匹配的步骤。
  2. 查看这些步骤是否在 JSON 数据中(使用 id 匹配)
  3. 删除任何不在提交的 JSON 中的内容。

因此,如果我删除带有recipe_step_id '8' 的行,这将被提交到路由,并且路由确定它不在数据中,将其从数据库中删除,然后根据路由处理其余数据.

因此,我当前的路线(显示添加/更新功能)是:

@app.route('/recipe/recipesteps/<int:recipe_id>/update', methods=['GET', 'POST'])
@login_required
def updaterecipesteps(recipe_id):
    recipe = Recipe.query.get_or_404(recipe_id)
    data = request.form
    nested_data = nest_once(data)
    for key, val in nested_data.items():
        recipe_step_id = val['recipe_step_id']
        recipe_step_temp = val['recipe_step_temp']
        recipe_step_name = val['recipe_step_name']
        recipe_id = recipe
        if recipe_step_id:
            recipe_step = ReciperecipeSteps.query.get_or_404(recipe_step_id)
            recipe_step.name = recipe_step_name
            recipe_step.step_temp = recipe_step_temp
            db.session.commit()
        else:
            recipe_step = ReciperecipeSteps(name=recipe_step_name,
                                        step_temp=recipe_step_temp,
                                        recipe_id=recipe_step.recipe_id)
            db.session.add(recipe_step)
            db.session.commit()
    return redirect(url_for('recipe', recipe_id=recipe.id))

我最接近这个的是这个查询:

mash_steps = RecipeSteps.query.filter(RecipeSteps.id.not_in([nested_data.recipe_step_id for val in nested_data.items]), RecipeSteps.recipe_id == recipe_id).all()

...但是 Python 不会遍历对象。

标签: flasksqlalchemy

解决方案


可能远不是最好的方法(我想我可以解析查询中的 JSON 数据),但这就是我的工作:

# Build a list from the step ids
step_id = []
for key, value in nested_data.items():
    recipe_step_id = value['recipe_step_id']
    step_id.append(recipe_step_id)
# Query matching items that aren't on the list
recipe_steps = RecipeSteps.query.filter(RecipeSteps.id.not_in(step_id), RecipeSteps.recipe_id == recipe.id).all()
# Loop through the results and delete 
for m in recipe_steps:
    db.session.delete(m)
db.session.commit()

推荐阅读