django ORM操作

BOYE / 2023-08-09 / 原文

from django.contrib.auth.models import User
from django.db.models import Q
from django.db.models.functions import Lower
from app.models import  *

添加操作a、使用create方式

方式一: Publish.objects.create("name"="人民出版社",city="北京"}
方式二: Publish.objects.create(**{"name":"文艺出版社","city":"上海"})

b、使用save方式
方式一:
book1=Book(title="python",price="88",publish_id="1",publication_date="2017-06-18")
book1.save()

方式二:
author1=Author(name="jerry")
author1.save()

user = User() 
user.username = '大侠'
user.password = '就是不告诉你密码
user.save()

#批量插入
Book.objects.bulk_create([])

#注:get_or_create,有就查询出来,没有就创建
 

  

查找操作

 

#按照age降序排序,然后再按照name升序排序
Student.objects.filter(school="阳关小学").order_by('-age', 'name')
#随机排序
Student.objects.order_by('?')

#按username升序排列
User.objects.order_by('username')
# 反序
User.objects.order_by('uid').reverse()

#从下标为4记录到下标为9的记录
User.objects.order_by('uid')[4:10] 

#values 指定字段
User.objects.all().values('username')

#去重  distinct
User.objects.values("password").distinct()[:10]

【基于双下划线的模糊查询】
__exact 精确等于 like 'aaa'
__iexact 精确等于 忽略大小写 ilike 'aaa'
__contains 包含 like '%aaa%'
__icontains 包含,忽略大小写 ilike '%aaa%',但是对于sqlite来说,contains的作用效果等同于icontains。

__startswith 以…开头
__istartswith 以…开头 忽略大小写
__endswith 以…结尾
__iendswith 以…结尾,忽略大小写
__range 在…范围内
__year 日期字段的年份
__month 日期字段的月份
__day 日期字段的日

Book.objects.filter(price__in=[100,200,300]) #price值等于这三个里面的任意一个的对象
Book.objects.filter(price__gt=100)  #大于,大于等于是price__gte=100,别写price>100,这种参数不支持
Book.objects.filter(price__lt=100)
Book.objects.filter(price__range=[100,200]) #sql的between and,大于等于100,小于等于200
Book.objects.filter(title__contains="python") #title值中包含python的
Book.objects.filter(title__icontains="python") #不区分大小写
Book.objects.filter(title__startswith="py") #以什么开头,istartswith 不区分大小写
Book.objects.filter(pub_date__year=2012)
Book.objects.filter(name__isnull=True) // 查询用户名为空的书

【F查询和Q查询】
from django.db.models import Q,F

#Q对象可以对关键字参数进行封装,从而更好的应用多个查询
#F查询专门取对象中某列值的操作,F的作用:用来批量修改数据的

#把table1表中的num列中的每一个值在的基础上加10
table1.objects.all().update(num=F("num")+10)
##查询table2表中以"aaa"开头的所有的title列
table2.objects.filter(Q(title__startswith="aaa")).all()

#查找以"aaa"开头,或者以"bbb"结尾的所有title
Q(title__startswith="aaa") | Q(title__endswith="bbb")

#查找以"aaa"开头,且不以"bbb"结尾的所有title
Q(title__startswith="aaa") & ~Q(title__endswith="bbb")

#查找以"aaa"开头,以"bbb"结尾的title且书的id号大于4的记录
Q(title__startswith="aaa") | Q(title__endswith="bbb"),book_id__gt=4

【聚合查询】
from django.db.models import Avg, Sum, Max, Min, Count

#计算图书价格的平均值
Book.objects.all().aggregate(avg_price=Avg('price'))
#计算图书价格的总和
Book.objects.all().aggregate(total_price=Sum('price'))
#找到图书价格的最大值
Book.objects.all().aggregate(max_price=Max('price'))

#按照图书标题的首字母进行分组,并计算每个组内图书价格的平均值
Book.objects.values('title__startswith').annotate(avg_price=Avg('price'))

  

  

  

更新操作

#使用save方法将所有属性重新设定一遍,效率低
author1=Author.objects.get(id=3)#获取id为3的作者对象
author1.name="jobs"#修改作者对象的名字
author1.save()#把更改写入数据库

#使用update方法直接设置对就的属性
Publish.objects.filter(id=2).update(name="北京出版社")
注意:update()是QuerySet对象的一个方法,get返回的是一个model对象,其没有update方法.
filter返回的是一个QuerySet对象,filter里可以设定多个过滤条件

data = {'username':'nick','is_active':'0'}
User.objects.filter(id=1).update(**data)

注:update_or_create:有就更新,没有就创建

  

删除操作

Book.objects.filter(id=1).delete()