MySQL聚合函数:
"""
max 统计最大值
min 统计最小值
sum 统计求和
count 统计计数
avg 统计平均值
"""
'''使用关键字段:aggregater'''
操作方法:
from django.db.models import Max, Min, Sum, Avg, Count
res = models.BOOK.objects.aggregater(Max('price'))
print(res)
res = models.Book.objects.aggregate(Max('price'),
Min('price'),
Sum('price'),
Avg('price'),
Count('pk')
)
print(res)
'''MySQL分组操作: group by 关键字: annotate'''
ORM执行分组操作,报错的话就去修改sql_mode 移除only_full_group_by
from django.db.models import Max, Min, Sum, Avg, Count
res = models.Book.objects.annotate(author_num=Count('authors__pk')).values('title', 'author_num')
print(res)
res = models.Publish.objects.annotate(min_price=Min('book__price')).values('name', 'min_price')
print(res)
res = models.Book.objects.annotate(author_num=Count('authors__pk')).filter(author_num__gt=1).values('title', 'author_num')
print(res)
res = models.Author.objects.annotate(book_sum_price=Sum('book__price')).values('name', 'book_sum_price')
print(res)
'''使用表中的字段分组'''
res = models.Book.objects.values('publish_id').annotate(book_num=Count('pk')).values('publish_id', 'book_num')
print(res)
"""
当表中已经有数据的情况下,添加额外的字段、需要指定默认值或者为null
方式一:
IntegerField(verbose_name='销量',default=1000)
方式二:
IntegerField(verbose_name='销量',null=True)
方式三:
在迁移命令提示中直接给默认值
"""
from django.db.models import F
res = models.Book.objects.filter(kucun__gt=F('xiaoliang'))
print(res)
res = models.Book.objects.update(price=F('price')+1000)
res = models.Book.objects.update(title=F('title')+'_爆款')
from django.db.models.functions import Concat
from django.db.models import Value
res = models.Book.objects.update(title=Concat(F('title'),Value('爆款')))
from django.db.models import Q
'''使用Q对象,我们就可以做逻辑运算符'''
res = models.Book.objects.filter(Q(price__gt=9888), Q(xiaoliang__gt=500))
print(res.query)
res = models.Book.objects.filter(Q(price__gt=9888) | Q(xiaoliang__gt=500))
print(res.query)
res = models.Book.objects.filter(~Q(price__gt=9888))
print(res.query)
'''
Q对象进阶用法
filter(price=100)
filter('price'=100)
当我们需要编写一个搜索功能 并且条件是由用户指定 这个时候左边的数据就是一个字符串
'''
q_obj = Q()
q_obj.connector = 'or'
q_obj.children.append(('price__gt', 9888))
q_obj.children.append(('xiaoliang__gt', 530))
res = models.Book.objects.filter(q_obj)
print(res)
"""
在IT行业,需要做到尽量不麻烦数据库就不麻烦数据库,
"""
res = models.Book.objects.all()
print(res)
res = models.Book.objects.values('title','price')
for i in res:
print(i.get('title'))
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.title)
print(obj.price)
print(obj.publish_time)
"""
defer与only相反,对象点括号内出现的字段就会走数据库查询, 点括号不存在的数据,也会得到,而且不走数据库查询
"""
res = models.Book.objects.select_related('publish')
for obj in res:
print(obj.title)
print(obj.publish.name)
print(obj.publish.addr)
"""
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)
"""
将多次查询之后的结果封装到数据对象中 后续对象通过正反向查询跨表 内部不会再走数据库查询
"""
AutoField() int auto_increment
CharField() 必须写max_length参数 varchar类型
IntergerField() int 整型
DecimalField() decimal
DateField()
date 两种 auto_now auto_now_add
DateTimeField()
datetime 两种 auto_now auto_now_add
BigIntergerField() bigint
BooleanField() 传布尔值 存0和1
TextField() 存储大段文本
FileField() 传文件自动保存到指定位置并存文件路径
EmailField() 本质还是varchar类型
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):
"""
返回真正的数据类型及各种约束条件
:param connection:
:return:
"""
return 'char(%s)' % self.max_length
myfield = MyCharField(max_length=32,null=True)
primary_key 主键
max_length 最长
verbose_name 简介
null 空
default 默认值
max_digits decimal最大长度
decimal_places 小数点后位数
unique 唯一
db_index 索引
auto_now 表改变自动更新
auto_now_add 创建记录添加日期
choices 类似于枚举
to 创建外键指定被关联内容
to_field 创建外键指定被关联自字段
db_constraint 是否在数据库中创建外键约束
related_name 修改正向查询的字段名
用于可以被列举完全的数据
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()
res = models.User.objects.get('pk=2')
res.get_gender_display()
当值为1 获取男性
当值为2 获取女性
当值为3 获取中性
当值不存在的时候, 直接返回输入的数值
"""
外键字段中使用related_name参数可以修改正向查询的字段名
"""
原子性
一致性
独立性
持久性
start transcation;
rollback;
commit;
from django.db import transaction
try:
with transaction.atomic():
pass
except Exception:
pass
from django.db import connection, connections
cursor = connection.cursor()
cursor.execute("""SELECT * from app01_author where id = %s""", [4])
res = cursor.fetchone()
print(res)
models.UserInfo.objects.extra(
select={'newid':'select count(1) from app01_usertype where id>%s'},
select_params=[1,],
where = ['age>%s'],
params=[18,],
order_by=['-age'],
tables=['app01_book']
)
res = models.Book.objects.extra(
select={'newid': 'select count(1) from app01_book where id>%s'},
select_params=[1, ],
)
print(res)
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 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?