要添加具有给定描述的项目,我使用:db.session.add(new_item)
。要删除项目:db.session.query(Item).filter_by(item_id=new_id).delete()
。要更新项目的某些部分:db.session.query(Item).filter_by(item_id=new_id).update({"status":"1 "})
。
如果我想完全编辑项目,即重新插入同一项目的数据,我应该使用什么?
这是表格的代码:
<form class="form" action="{{ url_for('new_item') }}" method="post" role="form" enctype=multipart/form-data>
{{ form.csrf_token }}
<table>
<tr>
<td>
<div class="form-group">
<label for="item_name">item name:</label>
<input name="name" type="text" class="form-control" id="item_name">
</div>
</td>
<td>
<div class="form-group">
<label for="item_price">item price</label>
<input name="price" type="number" class="form-control" id="item_price">
</div>
</td>
<td>
<div class="form-group">
<label for="photo">Download the photo</label>
<input type="file" name="file">
<p class="help-block">Download</p>
</div>
</td>
</tr>
<tr>
<td>
<div class="form-group">
<label for="item_category">Category:</label>
<select name="category" class="form-control" id="item_category">
<option>LEGO</option>
<option>Игры_и_игрушки</option>
<option>Малыш</option>
<option>Школа_и_канцтовары</option>
<option>Творчество_и_развитие</option>
</select>
</div>
</td>
</tr>
</table>
<div class="form-group">
<label for="item_description">Description of the item:</label>
<textarea name="description" class="form-control" id="item_description" rows="3"></textarea>
</div>
<button type="submit" class="btn btn-default">Save</button>
</form>
以下是表单的路径。还有其他人,更新项目并删除它,但我想这应该足够
@app.route('/admin_items', methods=['GET', 'POST'])
def admin_items():
form = AddItemForm(request.form)
available = db.session.query(Item).filter_by(status='1').order_by(Item.name.asc())
not_available = db.session.query(Item).filter_by(status='0').order_by(Item.name.asc())
return render_template('admin_items.html',
available_items=available,
not_available_items=not_available,
form=form)
@app.route('/add_item', methods=['GET', 'POST'])
@login_required
def new_item():
error = None
form = AddItemForm(request.form)
if request.method == 'POST':
file = request.files['file']
if file and allowed_file(file.filename) and form.name.data != "" and form.description.data != "":
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOADED_ITEMS_DEST'], filename))
new_item = Item(
filename,
form.name.data,
form.description.data,
form.price.data,
form.age.data,
form.particles.data,
form.category.data,
'1',
)
db.session.add(new_item)
db.session.commit()
return redirect(url_for('admin_items'))
else:
return render_template('admin_items.html', form=form, error=error)
if request.method == 'GET':
return redirect(url_for('admin_items'))
答案 0 :(得分:4)
您可以为更新子句.update({"status":"1", "colour":"red"})
指定更多元素,或者您可以从数据库中获取对象,只需根据需要进行更改:
item = db.session.query(Item).get(1) # grab the item with PK #1.
item.status = '1'
item.colour = 'red'
db.session.commit() # commit your changes to the database.