Django数据更新操作记住一下顺口溜:

对于修改一条数据,要一查二改三保存。对于批量数据,只要拿到一组queryset然后直接update即可,

思路:

前端传过来一个id,后端根据这个id获取数据并把数据返给前端,前端在本地更新需要修改的数据后回传给后端,后端接到值后更新数据库

示例:

1pc后台页面有一个更新按钮

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>

<table border="1" cellspacing=0 >
<tr bgcolor="#d3d3d3">
<th>id</th>
<th>title</th>
<th>pub</th>
<th>price</th>
<th>market_price</th>
<th>op</th>
</tr>
{% for book in data_book %}
<tr>
<td>{{ book.id }}</td>
<td>{{ book.title }}</td>
<td>{{ book.pub }}</td>
<td>{{ book.price }}</td>
<td>{{ book.market_price }}</td>
<td>
<a href="/bookstore/update_book/{{ book.id }}">更新</a>
<a>删除</a>
</td>
</tr>
{% endfor %}
</table>

</body>
</html>

2触发更新按钮弹出的页面:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>更改书籍</title>
</head>
<body>
<form action="/bookstore/update_book/{{ book.id }}" method="post">
<p>
title <input type="text" value="{{ book.id }}" disabled="disabled">
</p>
<p>
pub <input type="text" value="{{ book.pub }}" disabled="disabled">
</p>
<p>
price <input type="text" value="{{ book.price }}" name="price">
</p>
<p>
market_price <input type="text" value="{{ book.market_price }}" name="market_price">
</p>
<p>
<input type="submit" value="更新">
</p>
</form>
</body>
</html>

3后台定义更新页面的路由:

path('update_book/<int:book_id>',views.update_book),

4编写路由绑定的视图函数:

#更新书籍
def update_book(request, book_id):
try:
book = Book.objects.get(id=book_id) # #获取不到值会报错,所以加了try...except
except Exception as e:
print('--update book error is %s'%(e))
return HttpResponse('--The book is not existed')
if request.method == 'GET':
return render(request,'bookstore/update_book.html',locals())
elif request.method == 'POST':
#获取
price = request.POST['price']
market_price = request.POST['market_price']
#修改
book.price = price
book.market_price = market_price
#保存
book.save()
return HttpResponseRedirect('/bookstore/all_book')