Django-15 ORM 更新操作 圖書管理系統

  • 修改單個實體的某些字段值的步驟
  1. 查:通過 get() 得到要修改的實體對象
  2. 改:通過 對象.屬性 的方式修改數據
  3. 保存:通過 對象.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)

圖書管理系統


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>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章