Django 多表查询 聚合查询 分组查询 F查询 Q查询
# --------------------------------------------------------------------------------------------------------
# 三张表 出版社表 书籍表 作者表
#
# # 书籍表
# class Book(models.Model):
# name = models.CharField(max_length=20)
# price = models.IntegerField()
# pub_date = models.DateField()
# publish = models.ForeignKey("Publish")
# #authors = models.ManyToManyField("Author") #一般创建多对多关系 自己也可以创建一个多对多表关系 推荐单建立一个多表
# # authors 对应Author的id == authors_id authors.列名 能取到Author的数据
# def __str__(self):
# return self.name
#
# class Meta:
# db_table = "Book"
# # 出版社表
# class Publish(models.Model):
# name = models.CharField(max_length=32)
# city = models.CharField(max_length=32)
#
# def __str__(self):
# return self.name
#
# class Meta:
# db_table = "Publish"
# # 推荐自己创建一个多表 这种比较灵活
# # class Book_Author(models.Model):
# # book=models.ForeignKey("Book")
# # author=models.ForeignKey("Author")
# # 作者表
# class Author(models.Model):
# name = models.CharField(max_length=32)
# age = models.IntegerField(default=20)
#
# def __str__(self):
# return self.name
#
# class Meta:
# db_table = "Author"
# -------------------------------------------------------------------------------------------------------- # --------------------------------------------------------------------------------------------------------
# 多表关系 一对多操作
# 添加数据
# Book.objects.create(name="python", price=77, pub_date="2017-12-12", publish_id=2)
#
# publish_obj=Publish.objects.filter(name="人民出版社")[0]
# Book.objects.create(name="GO",price=23,pub_date="2017-05-12",publish=publish_obj) # book_obj=Book.objects.get(name="python") # 是一个对象
# print(type(book_obj))
# print(book_obj.name)
# print(book_obj.pub_date)
#
# #一对多:book_obj.publish--------一定是一个对象
# print(book_obj.publish.name)
# print(book_obj.publish.city)
# print(type(book_obj.publish))
#
# 查询人民出版社出过的所有书籍名字和价格
# select name,price from Book where publish_id in (select id from Publish where name="人民出版社");
# 方式一:
# pub_obj = Publish.objects.filter(name="人民出版社")[0]
# ret = Book.objects.filter(publish=pub_obj).values("name", "price")
# print(ret) # 方式二
# pub_obj = Publish.objects.filter(name="人民出版社")[0]
# print(pub_obj.book_set.all().values("name","price"))
# print(type(pub_obj.book_set.all())) # 方式三 推荐用这个 正向查询 神奇的双下划线 __
# 通过 filter values (双下换线)进行多对多的关联查询(形式和一对多)
#
# 查询人民出版社出的书名 和 书的价格
# SELECT `Book`.`name`, `Book`.`price` FROM `Book` INNER JOIN `Publish` ON (`Book`.`publish_id` = `Publish`.`id`) WHERE `Publish`.`name` = '人民出版社'
# ret=Book.objects.filter(publish__name="人民出版社").values("name","price")
# print(ret)
#
# python这本书出版社的名字 注意book要小写
# select name from Publish where id in (select publish_id from Book where name="python");
# SELECT `Publish`.`name` FROM `Publish` INNER JOIN `Book` ON (`Publish`.`id` = `Book`.`publish_id`) WHERE `Book`.`name` = 'python'
# ret2 = Publish.objects.filter(book__name="python").values("name")
# print(ret2)
# ret3 = Book.objects.filter(name="python").values("publish__name")
# print(ret3)
#
# 北京城市出的所有书
# select name from Book where publish_id in (select id from Publish where city="bj")
# SELECT `Book`.`name` FROM `Book` INNER JOIN `Publish` ON (`Book`.`publish_id` = `Publish`.`id`) WHERE `Publish`.`city` = 'bj'
# ret4 = Book.objects.filter(publish__city="bj").values("name")
# print(ret4) # 查询一段时间内出过书的出版社
# SELECT `Publish`.`name` FROM `Book` INNER JOIN `Publish` ON (`Book`.`publish_id` = `Publish`.`id`) WHERE (`Book`.`pub_date` < '2017-07-01' AND `Book`.`pub_date` > '2017-01-01')
# ret5=Book.objects.filter(pub_date__lt="2017-07-01",pub_date__gt="2017-01-01").values("publish__name")
# print(ret5)
# -------------------------------------------------------------------------------------------------------- # --------------------------------------------------------------------------------------------------------
# 多多关系 对对多操作
# 通过对象的方式绑定关系
# book_obj=Book.objects.get(id=3)
# print(book_obj.authors.all())
# print(type(book_obj.authors.all())) #查询id为2的作者出的书
# author_obj=Author.objects.get(id=2)
# print(author_obj.book_set.all()) # 多表操作 增加数据
# book_obj=Book.objects.get(id=37)
# author_objs=Author.objects.all()
# book_obj.authors.add(*author_objs) # 多表操作 删除数据
# # book_obj.authors.remove(*author_objs)
# book_obj.authors.remove(4) # 创建第三张表
# Book_Author.objects.create(book_id=38,author_id=1)
# Book_Author.objects.create(book_id=35,author_id=1)
# Book_Author.objects.create(book_id=37,author_id=1) # 查找book id是36的作者
# select name from Author where id in (select author_id from Book_Author where book_id = 35);
# ret = Author.objects.filter(book_author__book__id="35")
# obj_id = Book.objects.filter()
# print(ret) # 外键找外键关联的表 直接用fk找
# 没外键找和它有关联表用 外键的类_set找 注意 外键类小写 或者在外键上加上 related_name='自己的类名' 注意小写
ret = Book.objects.get(id=36).authors.all().values("name")
print(ret) # zhangsan出过的书籍名称及价格
# select name,price from Book where id in (select book_id from Book_Author where author_id in(select id from Author where name="zhangsan")));
# ret2=Book.objects.filter(book_author__author__name="zhangsan").values("name","price")
# ret2=Book.objects.filter(authors__name="zhangsan").values("name","price")
# print(ret2)
# ret1 = Author.objects.get(name="zhangsan").book_set.values("name","price")
ret1 = Author.objects.get(name="zhangsan").book_set.all()
print(ret1) # 找出 linux运维 这本书的作者是谁
#SELECT `Author`.`name` FROM `Author` INNER JOIN `Book_Author` ON (`Author`.`id` = `Book_Author`.`author_id`) INNER JOIN `Book` ON (`Book_Author`.`book_id` = `Book`.`id`) WHERE `Book`.`name` = 'linux运维';
#select name from Author where id in (select author_id from Book_Author where book_id in (select id from Book where name = "linux运维"));;
# ret = Author.objects.filter(book_author__book__name="linux运维").values("name")
ret2 = Book.objects.get(name="linux运维").authors.all().values("name")
print(ret2) # 聚合函数 aggregate
# ret=Book.objects.all().aggregate(Avg("price"))
# ret=Book.objects.all().aggregate(Sum("price"))
# ret=Book.objects.filter(authors__name="alex").aggregate(alex_money=Sum("price"))
# ret=Book.objects.filter(authors__name="alex").aggregate(Count("price"))
# print(ret) # ret=Book.objects.values("authors__name").annotate(Sum("price"))
# print(ret) # ret=Publish.objects.values("name").annotate(abc=Min("book__price"))
# print(ret) # b=Book.objects.get(name="GO",price=77)
# print(b) # Book.objects.all().update(price=F("price")+10) # ret=Book.objects.filter(Q(name__contains="G"))
# print(ret) # ret=Book.objects.filter(Q(name="GO"),price=87)
# print(ret) # ret=Book.objects.filter(price=200) # for i in ret:
# print(i.price)
#
# Book.objects.all().update(price=200)
# ret = Book.objects.filter(price=100)
# for i in ret:
# print(i.price) # if ret.exists():
# print("ok") # ret=ret.iterator()
# print(ret)
#
# for i in ret:
# print(i.name)
#
# for i in ret:
# print(i.name)
Django 多表查询 聚合查询 分组查询 F查询 Q查询的更多相关文章
- Django 08 Django模型基础3(关系表的数据操作、表关联对象的访问、多表查询、聚合、分组、F、Q查询)
Django 08 Django模型基础3(关系表的数据操作.表关联对象的访问.多表查询.聚合.分组.F.Q查询) 一.关系表的数据操作 #为了能方便学习,我们进入项目的idle中去执行我们的操作,通 ...
- Django模型系统——ORM中跨表、聚合、分组、F、Q
核心知识点: 1.明白表之间的关系 2.根据关联字段确定正反向,选择一种方式 在Django的ORM种,查询既可以通过查询的方向分为正向查询和反向查询,也可以通过不同的对象分为对象查询和Queryse ...
- Django ORM 之F、Q查询与事务
返回ORM目录 Django ORM 内容目录 一.F.Q查询 二.事务 三.only与defer 一.F.Q查询 """ Product表中的数据: 1 橡皮 2 20 ...
- Django orm进阶查询(聚合、分组、F查询、Q查询)、常见字段、查询优化及事务操作
Django orm进阶查询(聚合.分组.F查询.Q查询).常见字段.查询优化及事务操作 聚合查询 记住用到关键字aggregate然后还有几个常用的聚合函数就好了 from django.db.mo ...
- Django 聚合查询 分组查询 F与Q查询
一.聚合查询 需要导入模块:from django.db.models import Max, Min, Sum, Count, Avg 关键语法:aggregate(聚合结果别名 = 聚合函数(参数 ...
- Django 聚合分组F与Q查询及choices
一.聚合查询 需要导入模块:from django.db.models import Max, Min, Sum, Count, Avg 关键语法:aggregate(聚合结果别名 = 聚合函数(参数 ...
- Django中多表的增删改查操作及聚合查询、F、Q查询
一.创建表 创建四个表:书籍,出版社,作者,作者详细信息 四个表之间关系:书籍和作者多对多,作者和作者详细信息一对一,出版社和书籍一对多 创建一对一的关系:OneToOne("要绑定关系的表 ...
- django----聚合查询 分组 F与Q查询 字段 及其 参数
目录 一.orm补充查询 聚合查询 1-1 分组查询 1-2 F与Q查询 1-3 二. 字段及其参数 常用字段 AutoField IntegerField CharField DateField D ...
- django基础之day05,F与Q查询,Q查询的高级用法
#F与Q查询 #*************************** F 查询 ******************** # F 查询数据库中的其他字段!!! #1.查询库存数大于卖出数的书籍 fr ...
- django F与Q查询 事务 only与defer
F与Q 查询 class Product(models.Model): name = models.CharField(max_length=32) #都是类实例化出来的对象 price = mode ...
随机推荐
- (转)AIX下镜像制作与取消,更换硬盘问题
AIX下镜像制作与取消,更换硬盘问题 ROOTVG做镜像问题: 下面命令全部在AIX5.4上运行通过 # lspv hdisk0 000a1ddc7f36a2f0 rootvg ...
- python上安装requests
首先需要配置好python的环境变量. 测试是否成功配置,进入命令行,输入python. 如下图为配置成功. 去第三方库的网站下载安装包,解压在python的安装目录 ,下载地址:https://py ...
- warning: already initialized constant FileUtils::VERSION
Ran into this, and the solution here works: https://stackoverflow.com/questions/51334732/rails-5-2-0 ...
- Java虚拟机(二):JVM内存模型
所有的Java开发人员可能会遇到这样的困惑?我该为堆内存设置多大空间呢?OutOfMemoryError的异常到底涉及到运行时数据的哪块区域?该怎么解决呢?其实如果你经常解决服务器性能问题,那么这些问 ...
- 基于TrueLicense实现产品License验证功能
受朋友所托,需要给产品加上License验证功能,进行试用期授权,在试用期过后,产品不再可用. 通过研究调查,可以利用Truelicense开源框架实现,下面分享一下如何利用Truelicense实现 ...
- Ethereum 源码分析之 accounts
一.Account // Account represents an Ethereum account located at a specific location defined // by the ...
- Hadoop MapReduce流程及容错
shuffle流程 输入分片(input split):在进行map计算之前,mapreduce会根据输入文件计算输入分片(input split),每个输入分片(input split)针对一个ma ...
- HTTPS 接入优化建议
随着网络安全的普及成为共识,部署SSL证书完成HTTPS加密的站点 也随之增多.HTTPS加密能够带来的对身份验证及信息加密等诸多好处,不过想要HTTPS协议发挥更加完美的作用也需要开发者在相应环 ...
- Python urllib简单使用
Python的urllib和urllib2模块都做与请求URL相关的操作. 它们最显著的差异为: urllib2可以接受一个Request对象,并以此可以来设置一个URL的headers,但是urll ...
- awk 统计文件中按照某列统计某列的和(sum)
把第一列相同的名称的第二列加起来: [root@localhost cc]# cat 1.txtaaa 10 bbb 20aaa 30ccc 40ccc 20ccc 40 [root@localhos ...