Django ORM (三) 查询,删除

2023-01-31 00:01:45 django 查询 删除

ORM 查询操作

修改 views.py 文件

from Django.shortcuts import render, HttpResponse
from app01 import models
from  app01.models import Book,Author,Publisher

def data_oper(req):
    # 获取 book 表 id 为2的价格
    book = models.Book.objects.filter(id=2).values("price")
    print(book)

    # 获取 author 表 id 为 1 的名字
    authors = models.Author.objects.filter(id=1)[0]
    print(authors)

    # 获取 author 表 id 为 3 名字
    author1 = models.Author.objects.get(id=3)
    print(author1)

    # 以 id 为倒序排列输出记录
    author2 = models.Author.objects.order_by("-id")
    print(author2)

    return HttpResponse("Hello world")

反向查找

from djanGo.shortcuts import render, HttpResponse
from app01 import models
from  app01.models import Book,Author,Publisher

def data_oper(req):
    # 查找 Publish name 是 广东工业出版社 的 书籍
    obj=models.Publisher.objects.filter(name="广东工业出版社")[0]
    print(obj.book_set.all().values("title"))

    return HttpResponse("Hello world")

def data_oper(req):
    # 查找书籍名为 k8s 的出版社名字
    print(models.Publisher.objects.filter(book__title="K8S").values("name"))
    # 查找出版社名为 广东工业出版社 的书籍名字
    print(models.Book.objects.filter(publisher__name="广东工业出版社").values("title"))

    return HttpResponse("Hello world")

from django.shortcuts import render, HttpResponse
from app01 import models
from  app01.models import Book,Author,Publisher

def data_oper(req):
    # 查询所有出版社城市为 广州 的书名
   ret = models.Book.objects.filter(publisher__city='广州').values('title')
    print(ret)

    # 查询对应操作的sql语句
    print(ret.query)

    return HttpResponse("Hello world")

ORM 删除操作

修改 views.py 文件

from django.shortcuts import render, HttpResponse
from app01 import models
from  app01.models import Book,Author,Publisher

def data_oper(req):
    # 多对多的情况下,删除 book id 为1,author id 大于0的记录
    book = models.Book.objects.filter(id=2)[0]
    authors = models.Author.objects.filter(id__gt=0)
    book.authors.remove(*authors)

    # 删除单条记录,删除 book 表中 id 为 1 的记录
    models.Book.objects.filter(id=1).delete()



    return HttpResponse("Hello world")

ORM 更新操作

修改 views.py 文件

from django.shortcuts import render, HttpResponse
from app01 import models
from  app01.models import Book,Author,Publisher

def data_oper(req):
    # 把 author id 为 3 的 name 改为 katy
    author = models.Author.objects.get(id=3)
    author.name = "katy"
    author.save()

    return HttpResponse("Hello world")

相关文章