django

Django-15 ORM 更新操作

2021-07-15  本文已影响0人  JuliusL
  1. 查:通过 get() 得到要修改的实体对象
  2. 改:通过 对象.属性 的方式修改数据
  3. 保存:通过 对象.save() 保存数据
#将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.png
update_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>
上一篇下一篇

猜你喜欢

热点阅读