orm刪除數據
單個數據刪除
In [2]: b1=Book.objects.get(id=1)
In [3]: b1.delete()
Out[3]: (1, {'bookstore.Book': 1})
In [4]: Book.objects.all()
Out[4]: <QuerySet [<Book: Django_清華大學出版社_1.00_75.00>, <Book: JQury_機械工業出版社_90.00_85.00>, <Book: Linux_機械工業出版社_80.00_65.00>, <Book: HTML5_清華大學出版社_1.00_105.00>]>
In [5]: for i in Book.objects.all():
...: print(i.id)
...:
2
3
4
5
批量數據刪除
偽刪除
刪除實例
新增字段is_true
#is_true字段
class Book(models.Model):
title=models.CharField('書名',max_length=50,unique=True,default='')
pub=models.CharField('出版社',default='',max_length=100)
price=models.DecimalField('價格',max_digits=7,decimal_places=2)
market_price=models.DecimalField('圖書零售價',max_digits=7,decimal_places=2,default=0.0)
is_active=models.BooleanField('是否活躍',default=True)
def __str__(self):
return '%s_%s_%s_%s'%(self.title,self.pub,self.price,self.market_price)
數據庫遷移
E:\django_video_study\mysite2>python makemigrations
python: can't open file 'makemigrations': [Errno 2] No such file or directory
E:\django_video_study\mysite2>python manage.py makemigrations
Migrations for 'bookstore':
bookstore\migrations\0005_book_is_active.py
- Add field is_active to book
E:\django_video_study\mysite2>python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, bookstore, contenttypes, sessions
Running migrations:
Applying bookstore.0005_book_is_active... OK
E:\django_video_study\mysite2>
views.py
def all_book(request):
#all_book=Book.objects.all()
all_book=Book.objects.filter(is_active=True)
return render(request,'bookstore/all_book.html',locals())
def delete_book(request):
#通過獲取查詢字符串 book_id 拿到book的id
#將其is_active 改成False
#302跳轉至all_book
book_id=request.GET.get('book_id')
if not book_id:
return HttpResponse('請求異常')
try:
book=Book.objects.get(id=book_id,is_active=True)
except Exception as e:
print('---delete book get error %s'%(e))
return HttpResponse('獲取id錯誤')
#將其is_active改為False
book.is_active=False
book.save()
#302跳轉到all_book
return HttpResponseRedirect('/bookstore/all_book/')
all_book.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>顯示所有書籍</title>
</head>
<body>
<table border="1">
<tr>
<th>id</th>
<th>title</th>
<th>pu</th>
<th>price</th>
<th>market_price</th>
<th>op</th>
</tr>
{% for info in all_book %}
<tr>
<td>{{info.id}}</td>
<td>{{info.title}}</td>
<td>{{info.pub}}</td>
<td>{{info.price}}</td>
<td>{{info.market_price}}</td>
<td>
<a href="{% url 'update' info.id %}">更新</a>
<a href="/bookstore/delete_book?book_id={{info.id}}">刪除</a>
</td>
</tr>
{% endfor %}
</table>
</body>
</html>
urls.py
from django.urls import path
from . import views
urlpatterns=[
path('index',views.index),
path('all_book/',views.all_book,name='all_book'),
path('update/<int:book_id>/',views.update,name='update'),
path('delete_book/',views.delete_book)
]