Python学习第三十二课——ORM(多表查询,一对多)

多表查询首先要建立外键:

models.py(重要):

from django.db import models


# Create your models here.


# 一对多建表
class Book(models.Model):  # 表名
    name = models.CharField(max_length=20)  # name字段
    price = models.IntegerField()  # 字段
    pub_date = models.DateField()  # 字段
    publish = models.ForeignKey("Publish", on_delete=models.CASCADE) #Publish 是下面的类

    def __str__(self):
        return self.name


class Publish(models.Model):
    # 一个出版社可以出多本书,按道理一般将外键建立到多的一方
    name = models.CharField(max_length=32)
    city = models.CharField(max_length=32)


class Author(models.Model):
    name = models.CharField(max_length=32)
    age = models.IntegerField()

urls和HTML和上一章一样,此处省略!!!

views.py(核心代码):

from django.shortcuts import render, HttpResponse

# Create your views here.
from ap05.models import *


def index(request):
    return render(request, "index.html")


# 一对多的添加数据方法一:
# def addbook(request):
#     # 如果有外键,要加上外键的名字,而不是你创建的名字 系统默认在你创建外键名字后面加_id
#     Book.objects.create(name="linux", price=120, pub_date="2017-1-1", publish_id=2)
#     return HttpResponse("添加成功")

# 一对多的添加数据方法二:
def addbook(request):
    # 如果害怕出错,想用自己起的外键名字的话,就用方法二
    # public_obj=Publish.objects.get(name="北京出版社")
    # public_obj = Publish.objects.filter(name="北京出版社")[0] # filter返回的是一个集合
    # Book.objects.create(name="GIS", price=130, pub_date="2001-2-5", publish=public_obj) # 此时外键是自己起的名字

    # 根据书名查该书所对应的出版社
    bool_obj = Book.objects.get(name="python")  # 先按照书名查一条记录
    # print(bool_obj.name)
    # print(bool_obj.price)

    print(bool_obj.publish.name)  # 中国邮电出版社
    print(bool_obj.publish.city)  # 北京
    print(type(bool_obj.publish))  # .publish就是Publish对象

    # 查询北京出版社出过的所有书籍
    # 方法一:正向查询
    # pub_obj=Publish.objects.filter(name="北京出版社")[0]
    # ret=Book.objects.filter(publish=public_obj).values("name","price")
    # print(ret)


    # #方法二:反向查询
    # pub_obj=Publish.objects.filter(name="北京出版社")[0]
    # print(pub_obj.book_set.all()) # <QuerySet [<Book: JAVA>, <Book: C++>, <Book: C++>, <Book: GIS>, <Book: GIS>]>
    # print(pub_obj.book_set.all().values("name","price"))
    # print(type(pub_obj.book_set.all()))
    #
    return HttpResponse("添加成功")


def update(request): pass


def delete(request): pass


def select(request):
    # 方法二:反向查询
    pub_obj = Publish.objects.filter(name="北京出版社")[0]
    # print(pub_obj.book_set.all())  # <QuerySet [<Book: JAVA>, <Book: C++>, <Book: C++>, <Book: GIS>, <Book: GIS>]>
    book_list=pub_obj.book_set.all().values("name", "price")

    return render(request,"index.html",{"book_list1":book_list})

 

上一篇:mac、mac m1 打包asp.net core成docker


下一篇:drf框架 - 序列化组件 | ModelSerializer