[toc]python
Django之ORM字段及查询优化
一:经常使用字段
(1)AutoFiled字段:
(1)做用:mysql
(1)int自动递增字段,其必须传入primary_key = Truegit
(2)若是模型表中没有自增列 会自动建立一个名为id的自增列sql
(3)相似于主键字段数据库
(2)IntegerField:
(1)做用:django
(1)整数类型 其范围在-2147483648 to 2147483647(手机号不会用其存储 位数不够 通常使用字符串存储手机号)app
(2)至关于整形字段测试
(3)CharField:
(1)做用:优化
(1)字符类型 必须提供max_length参数atom
(2)至关于字符串类型
(3)其相似mysql中的varchar类型,在模型表中是没有char字段的
(3)DateField:
(1)做用:
(1)日期字段,年月日格式
(2)相似于python中datetime.time()
(4)DateTimeField:
(1)做用:
(1)日期字段,年月日格式
(2)相似于python中datetime.datetime()
(5)choice
(1)做用:
(1)存在某些对应关系
(2)例如:中文与英文对应 减小数据库的存储压力
(2)使用方式:
user_obj = models.User_info.objects.filter(pk=1).first() print(user_obj.gender) # 直接点字段 获取仍是数字 print(user_obj.get_gender_display()) # 男 get_gender_display() 固定使用方式 user_obj = models.User_info.objects.filter(pk=3).first() print(user_obj.get_gender_display()) # 3 若是没有和数字对应关系 不会报错 直接返回数字
常见字段类型:
AutoField(Field) - int自增列,必须填入参数 primary_key=True BigAutoField(AutoField) - bigint自增列,必须填入参数 primary_key=True 注:当model中若是没有自增列,则自动会建立一个列名为id的列 from django.db import models class UserInfo(models.Model): # 自动建立一个列名为id的且为自增的整数列 username = models.CharField(max_length=32) class Group(models.Model): # 自定义自增列 nid = models.AutoField(primary_key=True) name = models.CharField(max_length=32) SmallIntegerField(IntegerField): - 小整数 -32768 ~ 32767 PositiveSmallIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField) - 正小整数 0 ~ 32767 IntegerField(Field) - 整数列(有符号的) -2147483648 ~ 2147483647 PositiveIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField) - 正整数 0 ~ 2147483647 BigIntegerField(IntegerField): - 长整型(有符号的) -9223372036854775808 ~ 9223372036854775807 BooleanField(Field) - 布尔值类型 NullBooleanField(Field): - 能够为空的布尔值 CharField(Field) - 字符类型 - 必须提供max_length参数, max_length表示字符长度 TextField(Field) - 文本类型 EmailField(CharField): - 字符串类型,Django Admin以及ModelForm中提供验证机制 IPAddressField(Field) - 字符串类型,Django Admin以及ModelForm中提供验证 IPV4 机制 GenericIPAddressField(Field) - 字符串类型,Django Admin以及ModelForm中提供验证 Ipv4和Ipv6 - 参数: protocol,用于指定Ipv4或Ipv6, 'both',"ipv4","ipv6" unpack_ipv4, 若是指定为True,则输入::ffff:192.0.2.1时候,可解析为192.0.2.1,开启此功能,须要protocol="both" URLField(CharField) - 字符串类型,Django Admin以及ModelForm中提供验证 URL SlugField(CharField) - 字符串类型,Django Admin以及ModelForm中提供验证支持 字母、数字、下划线、链接符(减号) CommaSeparatedIntegerField(CharField) - 字符串类型,格式必须为逗号分割的数字 UUIDField(Field) - 字符串类型,Django Admin以及ModelForm中提供对UUID格式的验证 FilePathField(Field) - 字符串,Django Admin以及ModelForm中提供读取文件夹下文件的功能 - 参数: path, 文件夹路径 match=None, 正则匹配 recursive=False, 递归下面的文件夹 allow_files=True, 容许文件 allow_folders=False, 容许文件夹 FileField(Field) - 字符串,路径保存在数据库,文件上传到指定目录 - 参数: upload_to = "" 上传文件的保存路径 storage = None 存储组件,默认django.core.files.storage.FileSystemStorage ImageField(FileField) - 字符串,路径保存在数据库,文件上传到指定目录 - 参数: upload_to = "" 上传文件的保存路径 storage = None 存储组件,默认django.core.files.storage.FileSystemStorage width_field=None, 上传图片的高度保存的数据库字段名(字符串) height_field=None 上传图片的宽度保存的数据库字段名(字符串) DateTimeField(DateField) - 日期+时间格式 YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] DateField(DateTimeCheckMixin, Field) - 日期格式 YYYY-MM-DD TimeField(DateTimeCheckMixin, Field) - 时间格式 HH:MM[:ss[.uuuuuu]] DurationField(Field) - 长整数,时间间隔,数据库中按照bigint存储,ORM中获取的值为datetime.timedelta类型 FloatField(Field) - 浮点型 DecimalField(Field) - 10进制小数 - 参数: max_digits,小数总长度 decimal_places,小数位长度 BinaryField(Field) - 二进制类型
ORM字段与MySQL字段对应关系:
'AutoField': 'integer AUTO_INCREMENT', 'BigAutoField': 'bigint AUTO_INCREMENT', 'BinaryField': 'longblob', 'BooleanField': 'bool', 'CharField': 'varchar(%(max_length)s)', 'CommaSeparatedIntegerField': 'varchar(%(max_length)s)', 'DateField': 'date', 'DateTimeField': 'datetime', 'DecimalField': 'numeric(%(max_digits)s, %(decimal_places)s)', 'DurationField': 'bigint', 'FileField': 'varchar(%(max_length)s)', 'FilePathField': 'varchar(%(max_length)s)', 'FloatField': 'double precision', 'IntegerField': 'integer', 'BigIntegerField': 'bigint', 'IPAddressField': 'char(15)', 'GenericIPAddressField': 'char(39)', 'NullBooleanField': 'bool', 'OneToOneField': 'integer', 'PositiveIntegerField': 'integer UNSIGNED', 'PositiveSmallIntegerField': 'smallint UNSIGNED', 'SlugField': 'varchar(%(max_length)s)', 'SmallIntegerField': 'smallint', 'TextField': 'longtext', 'TimeField': 'time', 'UUIDField': 'char(32)',
自定义字段:
from django.db import models # Create your models here. #Django中没有对应的char类型字段,可是咱们能够本身建立 class FixCharField(models.Field): ''' 自定义的char类型的字段类 ''' 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): ''' 限定生成的数据库表字段类型char,长度为max_length指定的值 :param connection: :return: ''' return 'char(%s)'%self.max_length
二:经常使用字段参数
(1)null
(1)做用:
(1)表示某个字段能够设置为空
(2)当给模型表新增字段的时候能够将给字段设置为空 进行新增
(2)使用方式:
email = models.EmailField(null=True) # 将该字段设置为空
(2)unique
(1)做用:表示某个字段惟一 不能重复
(2)使用方式:
email = models.EmailField(unique=True) # 将该字段设置惟一 只是演示使用方式
(3)default
(1)做用:给某个字段设置默认值
(2)使用方式:
email = models.EmailField(default='110@qq.com') # 只是演示使用方式
(4)auto_now_add
(1)做用:建立数据记录的时候 会把当前时间记录
(2)使用方式:
create_time = models.DateField(auto_now_add=True)
(5)auto_now
(1)做用:只要数据被更新 当前时间都会被记录
(2)使用方式
create_time = models.DateField(auto_now=True)
三:关系字段
(1)ForeignKey
(1)做用:
(1)外键类型在ORM中用来表示外键关联关系,通常把ForeignKey字段设置在 '一对多'中'多'的一方。
(2)ForeignKey能够和其余表作关联关系同时也能够和自身作关联关系。
(1)字段参数
(1)to
(1)做用:设置要关联的表
(1)to_field
(1)做用:设置要关联的表的字段
(1)on_delete
(1)做用:当删除关联表中的数据时,当前表与其关联的行的行为。
(1)models.CASCADE
(1)做用:删除关联数据,与之关联也删除
(1)db_constraint
(1)做用:是否在数据库中建立外键约束,默认为True。
其他字段参数:
models.DO_NOTHING 删除关联数据,引起错误IntegrityError models.PROTECT 删除关联数据,引起错误ProtectedError models.SET_NULL 删除关联数据,与之关联的值设置为null(前提FK字段须要设置为可空) models.SET_DEFAULT 删除关联数据,与之关联的值设置为默认值(前提FK字段须要设置默认值) models.SET 删除关联数据, a. 与之关联的值设置为指定值,设置:models.SET(值) b. 与之关联的值设置为可执行对象的返回值,设置:models.SET(可执行对象)
使用方式:
def func(): return 10 class MyModel(models.Model): user = models.ForeignKey( to="User", to_field="id", on_delete=models.SET(func) )
(2)OneToOneField
(1)做用:
(1)一对一字段
(2)一般一对一字段用来扩展已有字段。(通俗的说就是一我的的全部信息不是放在一张表里面的,简单的信息一张表,隐私的信息另外一张表,之间经过一对一外键关联)
(2)字段参数
(1)to
(1)做用:设置要关联的表。
to_field
(1)做用:设置要关联的字段。
on_delete
(1)做用:当删除关联表中的数据时,当前表与其关联的行的行为。(参考上面的例子)
四:测试操做
(1)做用:在进行通常操做时先配置一下参数,使得咱们能够直接在Django页面中运行咱们的测试脚本
(2)在Python脚本中调用Django环境
这样就能够直接运行你的test.py文件来运行测试
(3)必知必会13条
操做下面的操做以前,咱们实现建立好了数据表,这里主要演示下面的操做,再也不细讲建立准备过程
<1> all(): 查询全部结果
*<2> filter(*kwargs): 它包含了与所给筛选条件相匹配的对象
*<3> get(*kwargs): 返回与所给筛选条件相匹配的对象,返回结果有且只有一个,若是符合筛选条件的对象超过一个或者没有都会抛出错误。
*<4> exclude(*kwargs): 它包含了与所给筛选条件不匹配的对象
<5> values(*field): 返回一个ValueQuerySet——一个特殊的QuerySet,运行后获得的并非一系列model的实例化对象,而是一个可迭代的字典序列
<6> values_list(*field): 它与values()很是类似,它返回的是一个元组序列,values返回的是一个字典序列
<7> order_by(*field): 对查询结果排序
<8> reverse(): 对查询结果反向排序,请注意reverse()一般只能在具备已定义顺序的QuerySet上调用(在model类的Meta中指定ordering或调用order_by()方法)。
<9> distinct(): 从返回结果中剔除重复纪录(若是你查询跨越多个表,可能在计算QuerySet时获得重复的结果。此时可使用distinct(),注意只有在PostgreSQL中支持按字段去重。)
<10> count(): 返回数据库中匹配查询(QuerySet)的对象数量。
<11> first(): 返回第一条记录
<12> last(): 返回最后一条记录
<13> exists(): 若是QuerySet包含数据,就返回True,不然返回False
(4)13个必会操做总结
返回QuerySet对象的方法有
(1)all()
(2)filter()
(3)exclude()
(4)order_by()
(5)reverse()
(6)distinct()
特殊的QuerySet
(1)values() 返回一个可迭代的字典序列
(2)values_list() 返回一个可迭代的元祖序列
返回具体对象的
(1)get()
(2)first()
last()
返回布尔值的方法有
exists()
返回数字的方法有
count()
将SQL语句打印到终端显示:
LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console':{ 'level':'DEBUG', 'class':'logging.StreamHandler', }, }, 'loggers': { 'django.db.backends': { 'handlers': ['console'], 'propagate': True, 'level':'DEBUG', }, } } 将SQL语句打印到终端显示
五:下划线单表查询
(1)表格数据
例如:
单表双下划线查询:
# 查询价格大于200的书籍 book_obj = models.Book.objects.filter(price__gt=200).first() print(book_obj) # 水浒传 # 查询价格小于200的数据 book_obj1 = models.Book.objects.filter(price__lt=200).values('title','price') print(book_obj1) # <QuerySet [{'title': '三国演义', 'price': Decimal('99.99')}, {'title': '红楼梦', 'price': Decimal('199.99')}]> # 查询价格小于等于199.99的书籍 book_obj = models.Book.objects.filter(price__lte=199.99).values('title','price') print(book_obj) # <QuerySet [{'title': '三国演义', 'price': Decimal('99.99')}, {'title': '红楼梦', 'price': Decimal('199.99')}]> # 查询价格大于于等于199.99的书籍 book_obj = models.Book.objects.filter(price__gte=199.99).values('title','price') print(book_obj) # <QuerySet [{'title': '水浒传', 'price': Decimal('1999.99')}, {'title': '西游记', 'price': Decimal('999.99')}]> # 价格要么是199,999,1999 python对数字不敏感 因此此时写成整形 res = models.Book.objects.filter(price__in=[199,999,1999]).values('title','price') print(res) # <QuerySet [{'title': '红楼梦', 'price': Decimal('199.00')}, {'title': '水浒传', 'price': Decimal('1999.00')}, {'title': '西游记', 'price': Decimal('999.00')}]> # 价格范围在(99-199)顾头顾尾 res1 = models.Book.objects.filter(price__range=(99,199)).values('title','price') print(res1) # <QuerySet [{'title': '三国演义', 'price': Decimal('99.00')}, {'title': '红楼梦', 'price': Decimal('199.00')}]> # 拿书名包含sr的 res2 = models.Book.objects.filter(title__contains='sr') print(res2) # <QuerySet [<Book: 水浒传sr>]> 仅仅只能去小写 res3 = models.Book.objects.filter(title__icontains='sr') print(res3) # <QuerySet [<Book: 三国演义SR>, <Book: 水浒传sr>]> 忽略大小写 # 查询书名以什么开头 res4 = models.Book.objects.filter(title__startswith='三') print(res4) # <QuerySet [<Book: 三国演义SR>]> res5 = models.Book.objects.filter(title__endswith='r') print(res5) # <QuerySet [<Book: 水浒传sr>]>
六:ForeignKey增删改查
(1)增长
例如:
# 方法一 models.Book.objects.create(title='聊斋',price=666.66,publish_id=2) # 方法二 book_obj = models.Publish.objects.filter(pk=2).first() models.Book.objects.create(title='你的名字',price=888.88,publish=book_obj)
PS:
(1)在方法一中 若是直接写表格中的字段 须要填写关联另一张表的主键
(2)在方法二中 经过获取另一张表生成的对象 而后在本地关联这个对象
(2)修改
例如:
# 数字版的 models.Book.objects.filter(pk=5).update(title='为了你 木子李') # 传对象版本的 publish_obj = models.Publish.objects.filter(name='南方').first() models.Book.objects.filter(title='为了你 木子李').update(publish=publish_obj)
(3)删除
models.Book.objects.filter(pk=5).delete()
(7)多对多增删改查
(1)增长
增长:
book_obj = models.Book.objects.filter(pk=10).first() res = book_obj.author # 跳到另一张表 res.add(1,2) # 给book添加了两个做者 author1 = models.Author.objects.filter(pk=1).first() author2 = models.Author.objects.filter(pk=2).first() book_obj = models.Book.objects.filter(pk=3).first() res = book_obj.author res.add(author1,author2)
PS:
(1)在添加值中 既能够写数字也能够写对象
(2)同时支持一次性填写多个
(2)修改
多表修改:
# 将主键为3的书本 做者改为id为5 book_obj = models.Book.objects.filter(pk=3).first() res = book_obj.author res.set(5) # 报错 'int' object is not iterable 必须传入一个可迭代对象 res.set([5,]) # # 将主键为10的书本 做者改为id为3和5 book_obj1 = models.Book.objects.filter(pk=10).first() author3 = models.Author.objects.filter(pk=3).first() author5 = models.Author.objects.filter(pk=5).first() res = book_obj1.author res.set([author3,author5])
PS:
(1)set()括号内 须要传一个可迭代对象 (2)可迭代对象中 能够是多个数字组合 (3)也能够是多个对象组合 可是不能混合使用
(3)删除
多表删除:
# 将主键为3的书籍做者删除 book_obj = models.Book.objects.filter(pk=3).first() res = book_obj.author res.remove(5) # 将主键值为10的对应做者id为3与5删除 book_obj = models.Book.objects.filter(pk=10).first() author3 = models.Author.objects.filter(pk=3).first() author5 = models.Author.objects.filter(pk=5).first() res = book_obj.author res.remove(author3,author5) # 将主键值为3的书籍所对应的做者都删除 book_obj = models.Book.objects.filter(pk=3).first() res = book_obj.author res.clear()
PS:
(1)remove()括号内既能够传数字 也能够传对象
(2)而且支持传对个 逗号隔开便可
(3)clear括号内不须要传任何参数 直接清除全部
八:多对多三种表格建立方式
(1)方式一:
class Book(models.Model): book_name = models.CharField(max_length=255) authors = models.ManyToManyField(to='Author') # 字段建立表格 class Author(models.Model): author_name = models.CharField(max_length=255)
PS:
(1)优势:第三张虚拟表不须要手动建立
(2)缺点:因为第三张表格本身没法操做 不能再虚拟表进行新的字段添加
(2)方式二
class Book(models.Model): book_name = models.CharField(max_length=255) class Author(models.Model): author_name = models.CharField(max_length=255) class Book2Author(models.Model): book = models.ForeignKey(to='Book') author = models.ForeignKey(to='Author') create_time = models.DateField(auto_now_add=True)
PS:
(1)优势:第三张关联表 本身建立 能够进行操做 添加新的字段
(2)缺点:可是ORM查询不方便 模型表中没有关联字段
(3)方式三
class Book(models.Model): book_name = models.CharField(max_length=255) ''' through:与哪张虚拟表作关联 through_fields:与虚拟表那个字段作关联 ''' authors = models.ManyToManyField(to='Author', through='Book2Author', through_fields=('book', 'author')) class Author(models.Model): author_name = models.CharField(max_length=255) class Book2Author(models.Model): book = models.ForeignKey(to='Book') author = models.ForeignKey(to='Author') create_time = models.DateField(auto_now_add=True)
PS:
(1)优势:虚拟表能够在建立新的字段,同时有关联字段
九:跨表查询
(1)正向与反向的概念
正反向概念:
一对一 正向:author---关联字段在author表里--->authordetail 按字段 反向:authordetail---关联字段在author表里--->author 按表名小写 一对多 正向:book---关联字段在book表里--->publish 按字段 反向:publish---关联字段在book表里--->book 按表名小写_set.all() 由于一个出版社对应着多个图书 多对多 正向:book---关联字段在book表里--->author 按字段 反向:author---关联字段在book表里--->book 按表名小写_set.all() 由于一个做者对应着多个图书
PS:
(1)正向查询经过关联字段
(2)反向查询经过表名小写便可
基础班多表查询:
# 1.查询书籍id是3 的出版社名称 book_obj = models.Book.objects.filter(pk=3).first() res = book_obj.publish # 关联字段 调到出版社表格 print(res.name) # 南方 # 2.查询书籍id是6 的做者姓名 book_obj = models.Book.objects.filter(pk=6).first() res = book_obj.author # print(res) # app01.Author.None 当查询结果又多个的时候 会显示None res1 = res.all() print(res1) # <QuerySet [<Author: SR>]> # 3.查询做者是SR的家庭住址 author_obj = models.Author.objects.filter(name='SR').first() res = author_obj. author_detail print(res.addr) # 南京 # 4.查询出版社是东方出版社出版的书籍 publish_obj = models.Publish.objects.filter(name='东方').first() res = publish_obj.book_set print(res) # app01.Book.None print(res.all()) # <QuerySet [<Book: 三国演义SR>]>
PS:
(1)若是查询结果有多个的时候 须要用到_set
(2)不然直接表名小写便可
正反向查询:
# 查询SR这个做者的年龄和手机号 #正向查询 author_obj = models.Author.objects.filter(name='SR').first() res = author_obj.author_detail print(res.addr) # 南京 print(res.phone) # 110 # 反向查询 res = models.AuthorDetail.objects.filter(author__name='SR').values('addr','phone') print(res) # <QuerySet [{'addr': '南京', 'phone': 110}]> # 查询手机号是130的做者年龄 # 正向 author_obj = models.AuthorDetail.objects.filter(phone=130).first() res = author_obj.author print(res.age) # 18 # 反向 res = models.Author.objects.filter(author_detail__phone=130).values('age') print(res) # <QuerySet [{'age': 18}]> # 查询书籍id是6 的做者的电话号码 book_obj = models.Book.objects.filter(pk=6).values('author__author_detail__phone') print(book_obj) # <QuerySet [{'author__author_detail__phone': 110}]> # 1.查询出版社为北方出版社的全部图书的名字和价格 res = models.Publish.objects.filter(name='北方出版社').values('book__title','book__price') print(res) # 2.查询北方出版社出版的价格大于19的书 res = models.Book.objects.filter(price__gt=19,publish__name='北方出版社').values('title','publish__name') print(res)
(2)聚合查询/分组查询:
聚合查询:
# 聚合查询(aggregate) from django.db.models import Max,Min,Count,Avg,Sum # res = models.Book.objects.aggregate(Sum('price')) res1 = models.Book.objects.aggregate(Avg('price')) res2 = models.Book.objects.aggregate(Count('price')) res3 = models.Book.objects.aggregate(Max('price')) res4 = models.Book.objects.aggregate(Min('price')) res5 = models.Book.objects.aggregate(Max('price'),Min('price'),Count('pk'),Avg('price'),Sum('price'))
分组查询:
# 统计每一本书的做者个数 from django.db.models import Max, Min, Count, Avg, Sum res = models.Book.objects.annotate(author_num = Count('authors')).values('author_num','title') # author_num 其别名 print(res) # 统计出每一个出版社卖的最便宜的书的价格 res = models.Publish.objects.annotate(mmp = Min('book__price')).values('name','mmp') print(res) # 统计不止一个做者的图书 res = models.Book.objects.annotate(author_num=Count('authors')).filter(author_num__gt=1) print(res)
(3)F/Q查询
(1)F查询:
(1)能够进行多个字段的比较
(2)本质就是从数据库获取某个字段的值
F查询:
# 查询库存数大于卖出数的书籍 res = models.Book.objects.filter(kucun__gt=F('maichu')) print(res) # 将书籍库存数所有增长1000 models.Book.objects.update(kucun=F('kucun')+1000) # 把全部书名后面加上'新款' from django.db.models.functions import Concat from django.db.models import Value ret3 = models.Book.objects.update(title=Concat(F('title'), Value('新款'))) models.Book.objects.update(title = F('title')+'新款') # 不能这么写
(2)Q查询
(1)filter()
等方法中逗号隔开的条件是与的关系。
(2)若是你须要执行更复杂的查询(例如OR
语句),你可使用Q对象
。
Q查询:
from django.db.models import Q # 查询书籍名称是三国演义或者价格是444.44 res = models.Book.objects.filter(title='三国演义',price=444.44) # filter只支持and关系 res1 = models.Book.objects.filter(Q(title='三国演义'),Q(price=444)) # 若是用逗号 那么仍是and关系 res2 = models.Book.objects.filter(Q(title='三国演义')|Q(price=444)) res3 = models.Book.objects.filter(~Q(title='三国演义')|Q(price=444)) print(res2)
Q高阶用法:
q = Q() q.connector = 'or' # 修改查询条件的关系 默认是and q.children.append(('title__contains','三国演义')) # 往列表中添加筛选条件 q.children.append(('price__gt',444)) # 往列表中添加筛选条件 res = models.Book.objects.filter(q) # filter支持你直接传q对象 可是默认仍是and关系 print(res)
十:事务
(1)做用:
(1)将多个sql操做变成原子性操做,要么同时成功 若是有一条数据失败了 则回滚
(2)保证数据的一致性
(2)使用方式:
# 事务 # 买一本 跟老男孩学Linux 书 # 在数据库层面要作的事儿 # 1. 建立一条订单数据 # 2. 去产品表 将卖出数+1, 库存数-1 from django.db.models import F from django.db import transaction # 开启事务处理 try: with transaction.atomic(): # 建立一条订单数据 models.Order.objects.create(num="110110111", product_id=1, count=1) # 能执行成功 models.Product.objects.filter(id=1).update(kucun=F("kucun")-1, maichu=F("maichu")+1) except Exception as e: print(e)