django之 基于queryset和双下划线的跨表查询

前面篇随笔写的是基于对象的跨表查询:对象.objects.filter(。。。)  对象.关联对象_set.all(...)  -->反向

基于对象的跨表查询例如:

    book_obj= Book.objects.filter(id=4).first() #注意多了个first
    print(book_obj) #go 这里得到的是一个models对象
    print(book_obj.publish.name) #桔子出版社

这篇随笔主要写的是基于双下划线的跨表查询,其本质是使用join连接其他表进行查询

一对多

def query(request):
    #正向查询
    ret1=Book.objects.filter(title='西游记').values("publish__name")
    print(ret1)  #<QuerySet [{'publish__name': '榴莲出版社'}]>
    print(ret1.first(),type(ret1.first())) #{'publish__name': '榴莲出版社'} <class 'dict'> 注意key 为 publish__name
    print(ret1.first()['publish__name']) # 榴莲出版社

    #反向查询
    ret2=Publish.objects.filter(book__title="西游记").values('name') #这里的book是表名称,book表里面有字段 title
    print('---------------------------------')
    print(ret2)  #<QuerySet [{'name': '榴莲出版社'}]>
    print(ret2.first()['name'])#榴莲出版社
  return HttpResponse('ok')

 多对多

#查询python书的作者的名字和年龄
def
query(request): #正向查询 ret = Book.objects.filter(title="python").values("authors__name","authors__age") print(ret) #注意结果的key #结果 <QuerySet [{'authors__name': 'wang', 'authors__age': 27}, {'authors__name': 'xiao', 'authors__age': 25}, {'authors__name': 'zhang', 'authors__age': 26}]> #反向查询 ret = Author.objects.filter(book__title="python").values("name","age") print(ret) #区分正向查询的key #结果 <QuerySet [{'name': 'wang', 'age': 27}, {'name': 'xiao', 'age': 25}, {'name': 'zhang', 'age': 26}]> return HttpResponse('ok')

 一对一

例子:查询名字为 xiao 的gf是什么
def
query(request): #正向查询 ret=Author.objects.filter(name='xiao').values('ad__gf') #Author设置了外键到 AuthorDetail print(ret) #<QuerySet [{'ad__gf': '刘诗诗'}]> #反向查询 ret=AuthorDetail.objects.filter(author__name='xiao').values('gf') print(ret) #<QuerySet [{'gf': '刘诗诗'}]> return HttpResponse('ok')

 下面进行跨多表查询,涉及三个表或者以上

#查询西瓜出版社出版过的书籍和书籍作者的名字
def
query(request): #正向 ret=Book.objects.filter(publish__name="西瓜出版社").values_list("title",'authors__name') print(ret) #<QuerySet [('三国演义', 'zhang'), ('python', 'xiao'), ('python', 'zhang'), ('python', 'wang')]> #反向 ret = Publish.objects.filter(name="西瓜出版社").values_list("book__title","book__authors__age","book__authors__name") print(ret) #<QuerySet [('三国演义', 26, 'zhang'), ('python', 25, 'xiao'), ('python', 26, 'zhang'), ('python', 27, 'wang')]> return HttpResponse('ok')

 

手机号以11开头的作者出版过的所有书籍名称以及出版社名称
def query(request):
#正向
ret = Book.objects.filter(authors__ad__tel__startswith="11").values("title","publish__name")
print(ret)
#< QuerySet[{'title': 'python', 'publish__name': '西瓜出版社'}, {'title': '三国演义', 'publish__name': '西瓜出版社'}] >
#反向
ret = Author.objects.filter(ad__tel__startswith="11").values("book__title","book__publish__name")
print(ret)
#<QuerySet [{'book__title': '三国演义', 'book__publish__name': '西瓜出版社'}, {'book__title': 'python', 'book__publish__name': '西瓜出版社'}]>
return HttpResponse('查询成功')

原文地址:https://www.cnblogs.com/mmyy-blog/p/9896650.html