django - ORM-更新操作
阿新 • • 發佈:2021-11-04
更新單個數據
修改單個實體的某些欄位值的步驟:
- 查
- 通過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)
練習 - 製作'更新書籍'的頁面
點選'檢視所有書籍'頁面中的'更新'進入更新頁面
檢視函式 update_book
url :http://127.0.0.1:8000/bookstore/update_book/<book_id>
更新頁中顯示當前書籍資訊,且能對 定價和零售價進行修改
# file : bookstore/views.py def update_book(request, book_id): # bookstore/update_book/1 try: book = Book.objects.get(id=book_id) 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')
<!-- file : bookstore/templates/bookstore/update_book.html --> <body> <form action="/bookstore/update_book/{{book.id}}" method="post"></form> <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> </body>
<!-- file : bookstore/templates/bookstore/all_book.html --> <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> <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 href="">刪除</a> </td> </tr> {% endfor %} </table> </body>
# file : bookstore/urls.py from django.urls import path from . import views urlpatterns = [ path('all_book', views.all_book), path('update_book/<int:book_id>', views.update_book) ]
輸入網址: http://127.0.0.1:8000/bookstore/all_book
點選 '更新',進入修改頁面
將 price 改成 10.00
點選 '更新',會自動跳轉到all_book頁面