模型类
from django.db import models
# Create your models here.
class Author(models.Model):
nid = models.AutoField(primary_key=True)
name = models.CharField(max_length=32)
age = models.IntegerField()
authorDetail = models.OneToOneField(to='AuthorDetail',on_delete=models.CASCADE)
class AuthorDetail(models.Model):
nid = models.AutoField(primary_key=True)
birthday = models.DateField()
telephone = models.CharField(max_length=15)
addr = models.CharField(max_length=64)
class Publish(models.Model):
nid = models.AutoField(primary_key=True)
name = models.CharField(max_length=32)
city = models.CharField(max_length=32)
email = models.EmailField()
class Book(models.Model):
nid = models.AutoField(primary_key=True)
title = models.CharField(max_length=32)
price = models.DecimalField(max_digits=5,decimal_places=2)
# publishDate = models.DateField()
publish = models.ForeignKey(to='Publish',to_field="nid",on_delete=models.CASCADE)
author = models.ManyToManyField(to='Author',)
视图函数
注释很清楚
from django.shortcuts import render,HttpResponse
from app01 import models
# Create your views here.
def query(request):
# 1.基于对象的查询(子查询),以依次查询的结果作为另一次查询的条件
# 1.1一对多
# 1.1.1正向查询book---pulish
# 1.1.1.1 查询python书籍出版社的邮箱
python = models.Book.objects.filter(title="python").first()
email = python.publish.email
print(email)
# 1.1.2反向查询,电子出版社出版的所有书籍名称,正向查询按字段,反向查询按表名小写_set.all()
books = models.Publish.objects.filter(name="电子出版社").last()
for obj in books.book_set.all():
print(obj.title)
# 1.2.1多对多,正向author.all();反向Book_set.all()
book = models.Book.objects.filter(title="python").first()
for author in book.author.all():
print(author.name)
# 1.2.2多对多反向查询
zhang = models.Author.objects.filter(name="张").first()
for book in zhang.book_set.all():
print(book.title)
# 基于queryset和__的查询(join查询)
# 正向查询按字段,反向查询:表明_字段
email = models.Book.objects.filter(title="python").values("publish__email")
print(email.query)
# 查找电子出版社书籍名称
# 方式1
book_name = models.Publish.objects.filter(name="电子出版社").values("book__title")
# 方式2
book_name = models.Book.objects.filter(publish__name="电子出版社").values("title")
print(book_name)
# 查询张的手机号
# 方式1
ret = models.Author.objects.filter(name="张").values("authorDetail__telephone")
# 方式2
ret = models.AuthorDetail.objects.filter(author__name="张").values("telephone")
# 查询手机号以154开头的作者出版过的书籍名称以及对应的出版社的名称,这样写真的超级简单啊!!!!!!
# 夸五张表
obj = models.Book.objects.filter(author__authorDetail__telephone__startswith="151").values("title","publish__name")
print(obj)
return HttpResponse("{}".format(email))