Django-15 ORM 更新操作
2021-07-15 本文已影响0人
JuliusL
-
修改单个实体的某些字段值的步骤
- 查:通过 get() 得到要修改的实体对象
- 改:通过 对象.属性 的方式修改数据
- 保存:通过 对象.save() 保存数据
-
批量更新数据
- 直接调用QuerySet的update(属性=值)实现批量修改
- 示例
#将id大于3的所有图书价格定为0
books = Book.objects.filter(id__gt=3)
books.update(price=0)
# 将所有图书的零售价定位100
books = Book.objects.all()
books.update(market_price=100)
图书管理系统
all_book.pngupdate_book.png
urlpatterns = [
path('all_book',views.all_book),
path('update_book/<int:book_id>',views.update_book)
]
from django.shortcuts import render
from .models import Book
from django.http import HttpResponse,HttpResponseRedirect
# Create your views here.
def all_book(request):
all_book = Book.objects.all()
return render(request,'bookstore/all_book.html',locals())
def update_book(request,book_id):
try:
book = Book.objects.get(id=book_id)
except:
print('---update book errer 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')
<body>
<form action="/bookstore/update_book/{{ book.id }}" method="post">
<p>
title <input type="text" value="{{ book.title }}" disabled="disabled">
</p>
<p>
pub <input type="text" value="{{ book.pub }}" disabled="disabled">
</p>
<p>
price<input type="text" name="price" value="{{ book.price }}">
</p>
<p>
market_price<input type="text" name="market_price" value="{{ book.market_price }}">
</p>
<p>
<input type="submit" value="更新">
</p>
</form>
</body>
<body>
<table border="1">
<tr>
<th>id</th>
<th>title</th>
<th>pub</th>
<th>price</th>
<th>market_price</th>
<th>op</th>
</tr>
{% for book in all_book %}
<tr>
<th>{{book.id}}</th>
<th>{{book.title}}</th>
<th>{{book.pub}}</th>
<th>{{book.price}}</th>
<th>{{book.market_price}}</th>
<th>
<a href="/bookstore/update_book/{{book.id}}">更新</a>
<a href="/">删除</a>
</th>
</tr>
{% endfor %}
</table>
</body>