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")
獲取除了 id 為2 的 book
book = models.Book.objects.exclude(id=2)
反向查找
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")