55-56 ORM多表查询
多表查询:
KEY ====》 通过ORM引擎如何跨表: 正向查询按字段,反向查询按表名小写
模型的创建:
from django.db import models # Create your models here.
class Book(models.Model):
title = models.CharField(max_length=32)
pub_date = models.DateField()
price = models.DecimalField(max_digits=6,decimal_places=2)
#publish 和book是一对多额关系
publish = models.ForeignKey(to="Publish",on_delete=models.CASCADE)
#book和author 表示多对多关系
authors = models.ManyToManyField(to="Author",db_table="book2authors") def __str__(self):
return self.title class Publish(models.Model):
name = models.CharField(max_length=32)
city = models.CharField(max_length=32)
email = models.CharField(max_length=32) def __str__(self):
return self.name class Author(models.Model):
name = models.CharField(max_length=32)
age = models.IntegerField()
#作者与作者详细信息时一对一关系
ad = models.OneToOneField(to="AuthorDetail",on_delete=models.CASCADE) def __str__(self):
return self.name class AuthorDetail(models.Model):
brithday = models.DateField()
tel = models.BigIntegerField()
addr = models.CharField(max_length=64) def __str__(self):
return str(self.tel)
一 基于对象的跨表查询( 子查询:以上一次的查询结果作为下一次的查询条件)
(1)一对多
正向查询:按字段 book.publish
Book对象 ---------------------------------- > Publish 对象
<---------------------------------
反向查询:按表名小写_set.all()
(2)多对多
正向查询:按字段 book.authors.all()
Book对象 ---------------------------------- > Author 对象
<---------------------------------
反向查询:按表名小写_set.all() ,#表名_set .all () 此处的set表示集合的意思
(3)一对一
正向查询:按字段 book.ad
Author 对象 ---------------------------------- > AuthorDetail 对象
<---------------------------------
反向查询:按表名小写
二 基于双下划綫的跨表查询:(相当于 mysql 中的 join)
left join on
通过 表名__该表名字段=“ 条件 ” , 表名__ 表示连表
结构: models.Book.objects.filter(条件).values(需要查询的字段)
#多表操作======》添加def add(request):
###############################绑定一对多关系############################################################
#方式一
# book = models.Book.objects.create(title="python", price=123, pub_date="2019-01-02", publish_id=1)
pub_obj = models.Publish.objects.filter(name="苹果出版社").first()
#
# book = models.Book.objects.create(title="python",price=123,pub_date="2019-01-02",publish=pub_obj)
# print(book.title) #python
# print(book.publish_id) #2
# print(book.publish)#苹果出版社,打印对象时,__str__ 返回的值 # 查询go出版社的邮箱
# book_go = models.Book.objects.filter(title="go").first()
# print(book_go.publish.email)
#############################绑定多对多关系,无非是在关系表中创建记录###################################### # linux这本书绑定两个作者:alex,egon
linux = models.Book.objects.filter(title="linux").first()
alex = models.Author.objects.filter(name="alex").first()
egon = models.Author.objects.filter(name="egon").first()
# linux.authors.add(alex.id,egon.id) #为什么不是这样写
# linux.authors.add(alex,egon) #重复的作者不会添加,不知道主键时用这种方式添加
# linux.authors.add(1,2) #这个也可以,已经知道主键用这种方式添加
# linux.authors.add(*[2,1])#相当于打散,一个个赋值
# linux.authors.remove(egon) #移除
# linux.authors.clear() 解除所有绑定
# linux.authors.set(1) #不能这样写
# linux.authors.set([1,]) #先清空,再添加,参数必须为一个列表
#
# 绑定多对多的方式:一定要找到关联属性在哪里,manytomany 关联属性authors,
# book.关联属性.add() book.关联属性.set([,]),book.关联属性.clear() #正向操作(关联字段所在的那个表开始)按字段,反向操作按表名小写
#给Alex添加两个书
linux = models.Book.objects.filter(title="linux").first()
go = models.Book.objects.filter(title="go").first()
alex = models.Author.objects.filter(name="alex").first()
#给Alex 作者绑定两本书籍:linux和go
alex.book_set.add(linux,go) return HttpResponse("添加成功!") # 一对一表的添加和一对多类似 作者表和作者详细表 #多表操作========》查询 def query(request):
##################################################基于对象的跨表查询############################################
# (1) 一对多
#1 查询linux 这本书籍的出版社的地址
正向查询
# linux = models.Book.objects.filter(title="linux").first()
# print(linux.publish.city)
# 2 查询苹果出版社出版的所有书籍
反向查询
# obj = models.Publish.objects.filter(name="苹果出版社").first()
# query = obj.book_set.all()
# print(query)
# (2) 多对多
# 1 查询linux书籍的所有作者
# linux = models.Book.objects.filter(title="linux").first()
# print(linux.authors.all()) # 2查询alex作者出版过得所有书籍
# alex = models.Author.objects.filter(name="alex").first()
# print(alex.book_set.all()) # (3)一对一
# 1 查询alex的手机号
# alex = models.Author.objects.filter(name="alex").first()
# print(alex.ad.tel)
# 2 查询手机号为911的作者的名字
# obj = models.AuthorDetail.objects.filter(tel=911).first()
# print(obj.authors.name) ###########################################基于双下划线的跨表查询##################################################
# 1 查询linux这本书籍的出版社的地址
# 方式一
# queryset = models.Book.objects.filter(title="linux").values("publish__city")
# print(queryset)
# print(queryset[0]["publish__city"])
# return HttpResponse("查询成功!")
#方式二
# queryset = models.Publish.objects.filter(book__title="linux").values("city")
# print(queryset)
# return HttpResponse("查询成功") # 2 查询linux书籍的所有作者
#正向查询
# queryset = models.Book.objects.filter(title="linux").values("authors__name")
# print(queryset)
#反向查询
# queryset = models.Author.objects.filter(book__title="linux").values("name")
# print(queryset)
# 3 查询alex的手机号
#正向查询
# queryset = models.Author.objects.filter(name="alex").values("ad__tel")
# print(queryset)
#反向查询
# queryset = models.AuthorDetail.objects.filter(author__name="alex").values('tel')
# print(queryset) # 连续跨表
# 4 查询人民出版社出版过的所有书籍的名字以及作者的姓名
# queryset = models.Book.objects.filter(publish__name="人民出版社").values("title","authors__name")
# print(queryset)
# queryset = models.Author.objects.filter(book__publish__name="人民出版社").values("book__title","name")
# print(queryset)
# 5 手机号以119开头的作者出版过的所有书籍名称以及出版社名称
queryset = models.Book.objects.filter(authors__ad__tel__startswith=119).values("title","publish__name")
print(queryset) return HttpResponse("查询成功")
待续
55-56 ORM多表查询的更多相关文章
- python 之 Django框架(orm单表查询、orm多表查询、聚合查询、分组查询、F查询、 Q查询、事务、Django ORM执行原生SQL)
12.329 orm单表查询 import os if __name__ == '__main__': # 指定当前py脚本需要加载的Django项目配置信息 os.environ.setdefaul ...
- 第十七篇 ORM跨表查询和分组查询---二次剖析
ORM跨表查询和分组查询---二次剖析 阅读目录(Content) 创建表(建立模型) 基于对象的跨表查询 一对多查询(Publish与Book) 多对多查询 (Author 与 Book) 一对一查 ...
- Django ORM多表查询练习
ORM多表查询 创建表结构: from django.db import models # 创建表结构 # Create your models here. class Class_grade(mod ...
- ORM单表查询,跨表查询,分组查询
ORM单表查询,跨表查询,分组查询 单表查询之下划线 models.Tb1.objects.filter(id__lt=10, id__gt=1) # 获取id大于1 且 小于10的值models ...
- 057.Python前端Django模型ORM多表查询
一 基于对象的查询 1.1 一对多查询 设计路由 from django.contrib import admin from django.urls import path from app01 im ...
- 57 ORM多表查询
多表查询from django.db import models# Create your models here. class Author(models.Model): nid = models. ...
- ORM多表查询下
一.多表查询 1.基于双下划线的跨表查询 Django 还提供了一种直观而高效的方式在查询(lookups)中表示关联关系,它能自动确认 SQL JOIN 联系.要做跨关系查询,就使用两个下划线来链接 ...
- django之orm单表查询
这几天重新学习了一下django的orm,以此作为记录来分享. Part1:修改配置,生成表 在写数据和查数据之前,首先先得把django配置一下,具体配置如下: 1.先在公共项目的settings中 ...
- Django 模版语法 测试环境 ORM单表查询
模版语法 传值 视图函数向前端html页面传值,基本上所有的数据类型都可以渲染在前端页面上. views.py from django.shortcuts import render, redirec ...
随机推荐
- 【入门】Gradle的基本使用、在IDEA中的配置、常用命令
一.介绍 java的源码构建工具,大致经历了 ant -> maven -> gradle 这个过程,每一次进步,都是在解决之前的工具所带来的问题,简单来说: 1. ant 功能虽然也很强 ...
- nginx的高可用集群
1,阿里云:SLB 2, 硬件负载均衡器(如:F5,RedWare ) 3,软件实现高可用或负载均衡.keepalived
- (转)Introductory guide to Generative Adversarial Networks (GANs) and their promise!
Introductory guide to Generative Adversarial Networks (GANs) and their promise! Introduction Neural ...
- (zhuan) Evolution Strategies as a Scalable Alternative to Reinforcement Learning
Evolution Strategies as a Scalable Alternative to Reinforcement Learning this blog from: https://blo ...
- (转) AdversarialNetsPapers
本文转自:https://github.com/zhangqianhui/AdversarialNetsPapers AdversarialNetsPapers The classical Pap ...
- Java二进制指令
转自: http://www.blogjava.net/DLevin/archive/2011/09/13/358497.html 指令从0x00-0xc9 没有0xba 常量入栈指令 指令码 操作码 ...
- entity framework浅谈
1. 什么是EF 微软提供的ORM工具. ORM让开发人员节省数据库访问代码的时间. 将更多的时间放在业务逻辑层面上. 开发人员使用linq语言, 对数据库进行操作. 2. EF的使用场景 EF有三种 ...
- C#中引用第三方ocx控件引发的问题以及解决办法
调用OCX控件的步骤:1.在系统中注册该ocx控件,命令:regsvr32.exe 控件位置(加 /u 参数是取消注册)2.在.net的工具箱中添加该控件,拖到form中去就可以了. 不用工具箱的话, ...
- 原创:R包制作--windows
1.下载安装Rtools,添加环境变量: 打开R,分别输入下面指令,看有无包错: system('g++ -v') system('where make') 2.package.skeleton()函 ...
- 恢复Intellij idea删除的文件
恢复Intellij idea的删除文件方法: 右键单机项目名称---->Local History---->Show History 可以看到历史操作记录,右键单机想要恢复的文件---- ...