from django.shortcuts import render,HttpResponse
# Create your views here.
from app01 import models
def query(request):
# #################### Object-based query (subquery) ##################### #########
# By field (publish)
# One-to-many book -----------------> publish
# <--------- -------
# book_set.all ()
# Forward query by field:
# Query the mailbox of the publisher of this book in python
# python=models.Book.objects.filter(title="python").first()
# print(python.publish.email)
# Reverse query lowercase by table name _set.all ()
# Books published by Apple Press
# publish_obj=models.Publish.objects.filter(name="苹果出版社").first()
# for obj in publish_obj.book_set.all():
# print(obj.title)
# By field (authors.all ())
# Many-to-many book -----------------------> author
# <-------- --------
# book_set.all ()
# Query the age of the python author
# python = models.Book.objects.filter (title = "python"). First ()
# for author in python.authors.all ():
# print (author.name, author.age)
# Query the titles of books published by alex
# alex=models.Author.objects.filter(name="alex").first()
# for book in alex.book_set.all():
# print(book.title)
# By field authorDetail
# Many-to-many author -----------------------> authordetail
# <-------------- -
# Author by table name
#Query the phone number of alex # alex = models.Author.objects.filter (name = 'alex'). First ()
# print (alex.authorDetail.telephone)
# Query the author's name in Shandong
# ad_list=models.AuthorDetail.objects.filter(addr="shandong")
#
# for ad in ad_list:
# print(ad.author.name)
'' '
Corresponds to sql:
select publish_id from Book where title="python"
select email from Publish where nid = 1
'''
# #################### Based on queryset and __query (join query) ################## ##########
# Forward query: reverse query by field: lowercase table name
# Query the mailbox of the publisher of python this book
# ret = models.Book.objects.filter (title = "python"). Values ("publish__email")
# print (ret.query)
'''
select publish.email from Book
left join Publish on book.publish_id=publish.nid
where book.title="python"
'''
# Apple Press Publishing Book Name
# Method 1:
ret1 = models.Publish.objects.filter (name = "Apple Press"). Values ("book__title")
print ("111111111 ====>", ret1. query) #Method
2:
ret2 = models.Book.objects.filter (publish__name = "Apple Press"). values ("title")
print ("2222222222 ====>", ret2.query)
#Query alex 的 手机 号
# Method 1:
ret = models.Author.objects.filter (name = "alex"). Values ("authorDetail__telephone")
# 方式2:
models.AuthorDetail.objects.filter(author__name="alex").values("telephone")
# Query the name of the book published by the author whose cell phone number starts with 151 and the name of the publisher corresponding to the book
ret=models.Book.objects.filter(authors__authorDetail__telephone__startswith="151").values('title',"publish__name")
print(ret.query)
return HttpResponse("OK")