ORM复习

 
####################### 基于对象查询(子查询) #######################
#
############## 1.一对多 ##############
# book ------> publisher
## 正向查询(正向查询按字段)
# python_obj = models.Book.objects.filter(title="python书籍").first()
# print(python_obj.publisher.name)
## 反向查询(反向查询按表名小写_set.all())
# publisher_obj = models.Publisher.objects.filter(name="xx出版社").first()
# for obj in publisher_obj.book_set.all():
#     print(obj.title)
#     
############## 2.多对多 ##############
# book ------> author
## 正向查询
# python_obj = models.Book.objects.filter(title="python书籍").first()
# for obj in python_obj.author.all():
#     print(obj.name, obj.age)
#     
## 反向查询
# author_obj = models.Author.objects.filter(name="changwoo").first()
# for obj in author_obj.book_set.all():
#    print(obj.title)
############## 3.一对一 ##############
# author ------> authordetail
# 正向查询 查找changwoo的手机号
# changwoo = models.Author.objects.filter(name="changwoo").first()
# print(changwoo.AuthorDetail.telephone)
# 反向查询 查找家在北京的作者
# beijing = models.AuthorDetail.objects.filter(addr="beijing").first()  # 仅查找第一个家在北京的作者
# print(beijing.Author.name)
# beijing_list = models.AuthorDetail.objects.filter(addr="beijing")  # 查找所有家在北京的作者
# for beijing in beijing_list:
#    print(beijing.Author.name)
#    
#    
####################### 基于QuerySet和双下划綫__查询(join查询) #######################
# 正向查询按字段,反向查询按表名
#
# 查询python这本书籍的出版社的邮箱
# select publisher.email from Book left join Publisher on book.publisher_id=publisher.id where book.title="python" 
# ret = models.Book.objects.filter(title="python").values("publisher__email")  # 方式一
# ret = models.Publisher.objects.filter(book__title="python").values("email")  # 方式二
# print(ret.query)  # 会打印对应的sql语句
# 查询手机号以151开头的作者出版过的书籍名称以及书籍对应的出版社名称
# models.Book.objects.filter(book__author__authordetail__startswith="151").values("book.title", "publisher.name")
 
####################### 聚合与分组 #######################
    ############## 1.聚合 ##############
    # from django.db.models import Sum, Count, Min, Max, Avg
    # ret = models.Person.objects.all().aggregate(age_sum=Avg("age"))  # aggregate是queryset终止函数 打印出字典类型{'age_avg': 232}
    # print(ret)
    ############## 2.分组 ##############
    # 跨表分组查询
    # select dept.name,Count(*) form person left join dept on person.dept_id=dept.id group by dept.name
    # ret = models.Person.objects.values('dept__name').annotate(c=Count('dept')).values('dept__name', 'c')  # annotate返回的是queryset
    # print(ret)
 

转载于:https://www.cnblogs.com/changwoo/p/9627082.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值