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")
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")