class BookManager(models.Manager): # 改變查詢集的結果集 def all(self): books = super().all() # QuerySet books = books.filter(isDelete=False) return books # 封裝函... ...
class BookManager(models.Manager): # 改變查詢集的結果集 def all(self): books = super().all() # QuerySet books = books.filter(isDelete=False) return books # 封裝函數:操作模型類對應的數據表(增刪改查) def create_book(self, title, author): # book = BookInfo() # 另一個模型類 model_class = self.model # 可以獲取當前模型類名,代替上一條代碼 book = model_class book.title = title book.author = author book.save() return book
class BookInfo(models.Model):
title = models.CharField(max_length=20)
author = models.CharField(max_length=10)
objects = BookManager() # 自定義BookManager類的對象
==================================================================
# objects 是自己定義的,並非模型類裡面的預設的 objects
# 顯示的結果將是未被邏輯刪除的數據
>>> BookInfo.objects.all()
>>> BookInfo.objects.create_book('了不起的蓋茨比', '菲茨傑拉德')