聚合查询
MySQL聚合函数:max \min \sum \count\avg
from django.db.modles import Max,Min,Sum,Avg,Count
res = models.Book.objects.aggregate(Max('price' ))
print (res)
'''没有分组也能使用聚合函数 默认整体就是一组'''
res = models.Book.objects.aggregate(Max('price' ),Min('id' ),Avg('price' ),Count('id' ))
print (res)
分组查询
MySQL分组操作:group by
ORM执行分组操作 如果报错 可能需要去修改sql_mode 移除only_full_group_by
'''上述操作都是以为单位做分组 如果想要以表中的某个字段分组如何操作'''
res = models.Book.objects.values('publish_id' ).annotate(book_num=Count('pk' )).values('publish_id' ,'book_num' )
print (res)
F与Q查询
'''
当表中已经有数据的情况下 添加额外的字段 需要指定默认值或者可以为null
方式1
IntegerField(verbose_name='销量',default=1000 )
方式2
IntegerField(verbose_name='销量',null=True)
方式3
在迁移命令提示中直接给默认值
'''
res = models.Book.objects.filter (price__gt = F('id' ))
print (res)
res = models.Book.objects.update(price = F('price' ) + 1000 )
from django.db.models.functions import Concat
from django.db.models import Value
res = models.Book.objects.update(title=Concat(F('title' ),Value('_爆款' )))
'''
filter括号内多个条件默认是and关系 无法直接修改
Q对象支持逻辑运算符:
, 代表and
| 代表or
~ 代表not
'''
from import .db.modles import Q
res = models.Book.objects.filter (Q(price__gt=20000 ) | Q(maichu__gt=1000 ))
filter (Price=100 )
filter ('price' =100 )
当我们需要编写一个搜索功能 并且条件是由用户指定 这个时候左边的数据就是一个字符串
q_obj = Q()
q_obj.connector = 'or'
q_obj.children.append(('price__gt' ,20000 ))
q_obj.children.append(('maichu__gt' ,1000 ))
res = models.Book.objects.filter (q_obj)
print (res.query)
ORM查询优化
在IT行业 针对数据库 需要尽量做 能不'麻烦' 它就不'麻烦' 它
光编写orm语句并不会直接指向SQL语句 只有后续的代码用到了才会执行
only与defer
'''需求:单个结果还是以对象的形式展示 可以直接通过句点符操作'''
res = models.Book.objects.only('title' , 'price' )
for obj in res:
print (obj.title)
print (obj.price)
print (obj.publish_time)
"""
only会产生对象结果集 对象点括号内出现的字段不会再走数据库查询
但是如果点击了括号内没有的字段也可以获取到数据 但是每次都会走数据库查询
"""
res = models.Book.objects.defer('title' ,'price' )
for obj in res:
print (obj.publish_time)
"""
defer与only刚好相反 对象点括号内出现的字段会走数据库查询
如果点击了括号内没有的字段也可以获取到数据 每次都不会走数据库查询
"""
select_related和prefetch_related
"""
select_related括号内只能传一对一和一对多字段 不能传多对多字段
效果是内部直接连接表(inner join) 然后将连接之后的大表中所有的数据全部封装到数据对象中
后续对象通过正反向查询跨表 内部不会再走数据库查询
"""
res = models.Book.objects.prefetch_related('publish' )
for obj in res:
print (obj.title)
print (obj.publish.name)
print (obj.publish.addr)
"""
将多次查询之后的结果封装到数据对象中 后续对象通过正反向查询跨表 内部不会再走数据库查询
"""
ORM常见字段
字段
说明
AutoField
int自增列,必须填入参数 primary_key=True。当model中如果没有自增列,则自动会创建一个列名为id的列。
IntegerField
一个整数类型
CharField
字符类型,必须提供max_length参数
DecimalField
DateField
日期类型 date
DateTimeField
日期类型 datetime
BooleanField
布尔类型 存0和1
TextField
存储大段文本
FileField
传文件自动保存到指定的位置并存储路径
class MyCharField (models.Field):
def __init__ (self, max_length, *args, **kwargs ):
self.max_length = max_length
super ().__init__(max_length=max_length, *args, **kwargs)
def db_type (self, connection ):
return 'char(%s)' % self.max_length
重要参数
参数
说明
primary_key
设置一对多外键字段
max_length
获取长度
verbose_name
起别名
null
设置为空
default
默认值
max_digits
最大位数
decimal_place
小数位数
unique
唯一
db_index
设置索引
auto_now
共享数据记录 更新时间
auto_now_add
创建记录把当前时间添加到数据库
用于可以被列举完全的数据
eg:性别 学历 工作经验 工作状态
class User (models.Model):
username = models.CharField(max_length=32 )
password = models.IntegerField()
gender_choice = (
(1 ,'男性' ),
(2 ,'女性' ),
(3 ,'变性' )
)
gender = models.IntegerField(choices=gender_choice)
user_obj.get_gender_display()
to
to_field
db_constraint
ps:外键字段中可能还会遇到related_name参数
"""
外键字段中使用related_name参数可以修改正向查询的字段名
"""
事物操作
MySQL事物:四大特性(ACID)
原子性
一致性
独立性
持久性
from django.db import transaction
try :
with transaction.atomic():
pass
except Exception:
pass
ORM执行原生SQL
from django.db import connection,connections
cursor = connection.cursor()
cursor = connections['default' ].cursor()
cursor.execute('''SELECT * from auth_user where id = %s''' , [1 ])
cursor.fetchone()
models.UserInfo.objects.extra(
select={'newid' :'selectcount(1) from app01_usertype where id>%s' },
where=['age>%s' ],
params=[18 ,],
order_by=[-age],
tables=['app01_usertype' ])
多对多三种创建方式
orm自动创建第三张表 但是无法扩展第三张表的字段
authors = models.ManyToManyField(to='Author' )
优势在于第三张表完全自定义扩展性高 劣势在于无法使用外键方法和正反向
class Book (models.Model):
title = models.CharField(max_length=32 )
class Author (models.Model):
name = models.CharField(max_length=32 )
class Book2Author (models.Model):
book_id = models.ForeignKey(to='Book' )
author_id = models.ForeignKey(to='Author' )
正反向还可以使用 并且第三张表可以扩展 唯一的缺陷是不能用
add\set \remove\clear四个方法
class Book (models.Model):
title = models.CharField(max_length=32 )
authors = models.ManyToManyField(
to='Author' ,
through='Book2Author' ,
through_fields=('book' ,'author' )
)
class Author (models.Model):
name = models.CharField(max_length=32 )
'''多对多建在任意一方都可以 如果建在作者表 字段顺序互换即可'''
books = models.ManyToManyField(
to='Author' ,
through='Book2Author' ,
through_fields=('author' ,'book' )
)
class Book2Author (models.Model):
book = models.ForeignKey(to='Book' )
author = models.ForeignKey(to='Author' )
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)