Django 自定义模型管理器类2个应用场景
程序员文章站
2023-01-14 20:29:19
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('了不起的盖茨比', '菲茨杰拉德')
上一篇: Scrapy的日志等级和请求传参
下一篇: Python-数据结构和算法之20问答