标签:cas 默认 upd 示例 ret obj ice import ade
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")
from django.http import HttpResponse
from .models import Pulisher, BookOrder
def index(request):
# 一次性的更新
BookOrder.objects.update(price=F('price')+5)
return HttpResponse("success")
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
标签:cas 默认 upd 示例 ret obj ice import ade
原文地址:https://www.cnblogs.com/guyan-2020/p/12272482.html