django-orm删除数据

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)
]
posted @ 2021-08-10 19:09  yescarf  阅读(1765)  评论(0编辑  收藏  举报