91.一次性处理多条数据的方法:bulk_create,update,delete

(1)bulk_create: 可以一次性的创建多个对象

示例代码如下:
from django.http import HttpResponse
from .models import Pulisher, BookOrder


def index(request):
    publisher =Publisher.objects.bulk_create([
        Publisher(name='hello出版社'),
        Publisher(name='你好出版社')
    ])
    return HttpResponse("success")

(2)update:可以一次性的更新所有的数据。

示例代码如下:
from django.http import HttpResponse
from .models import Pulisher, BookOrder


def index(request):
    # 一次性的更新
    BookOrder.objects.update(price=F('price')+5)
    return HttpResponse("success")

(3)delete:一次性的把所有的满足条件的数据都删除掉,但是需要注意的是,删除数据的时候,要注意定义的外键在删除时处理的方式:on_delete。

示例代码如下:
from django.http import HttpResponse
from .models import Pulisher, BookOrder


def index(request):
    # delete: 一次性的删除多满足条件的数据
    BookOrder.objects.filter(pk__gte=5).delete()
    return HttpResponse("success")

其中所使用的到的模型的定义文件models.py,示例代码如下:

from django.db import models


# 定义作者模型
class Author(models.Model):
    name = models.CharField(max_length=100, unique=True)
    age = models.IntegerField()
    email = models.EmailField()

    class Meta:
        db_table = 'author'

    def __str__(self):
        return "%s,%s,%s" % (self.name,self.age, self.email)


# 定义出版社模型
class Publisher(models.Model):
    name = models.CharField(max_length=100,unique=True)

    class Meta:
        db_table = 'publisher'

    def __str__(self):
        return " ->:%s" % self.name


def Publisher_Default():
    return Publisher.objects.get_or_create(name='默认出版社')


# 定义图书模型
class Book(models.Model):
    name = models.CharField(max_length=100, unique=True)
    pages = models.IntegerField()
    price = models.FloatField()
    rating = models.FloatField()
    author = models.ForeignKey('Author', on_delete=models.CASCADE)
    publisher = models.ForeignKey('Publisher', on_delete=models.SET_DEFAULT, default=Publisher_Default)
    score = models.FloatField(null=True)

    class Meta:
        db_table = 'book'

    # def __str__(self):
    #     return "(书名:%s,页数:%s,价格:%s,打折:%s,作者:%s,出版社:%s)" % (self.name, self.pages, self.price, self.rating, self.author, self.publisher)


# 定义预定图书的模型
class BookOrder(models.Model):
    book = models.ForeignKey('Book', on_delete=models.CASCADE)
    price = models.FloatField()
    time = models.DateTimeField(auto_now_add=True, null=True)

    class Meta:
        db_table = 'book_order'

你可能感兴趣的:(91.一次性处理多条数据的方法:bulk_create,update,delete)