Django的model中的Manager对象

Django的model中的Manager对象

当我们在执行ORM的增删改查操作时,一般会这样写:

python 复制代码
from app01 import models

models.Depart.objects.all(..)
models.Depart.objects.filter(..)
models.Depart.objects.create(..)

但是有时候我们需要自定义一些操作来实现某种功能,比如

python 复制代码
models.Depart.objects.xxxxx(...)

这时候我们就需自定义我们的Manager对象

python 复制代码
from django.db import models


class MyManager(models.Manager):
    def xxxxx(self, title):
        models.Depart.objects.create(title=title)
        models.Depart.objects.create(title=title)


class Depart(models.Model):
    title = models.CharField(verbose_name="标题", max_length=32)
    count = models.IntegerField(verbose_name="数量")

    objects = MyManager()

这样就实现了当我们执行models.Depart.objects.xxxxx(...)时,会在表中创建2条数据

相关推荐
kfaino2 小时前
码农的AI翻身(五)你好,我叫 Transformer
后端·aigc
Oneslide7 小时前
机械革命 单系统纯净重装Ubuntu(全盘覆盖,清空原有Windows)
后端
GetcharZp7 小时前
告别OOM!用Go+libvips实现30000×50000超大图片的流式瓦片服务
后端·go
IT_陈寒8 小时前
JavaScript项目实战经验分享
前端·人工智能·后端
用户47949283569159 小时前
6w star,GitHub 趋势第一的 Ponytail,这个agent插件到底在火什么
前端·后端
神奇小汤圆10 小时前
2026一线大厂Java八股文精选(附答案,高质量整理)
后端
Warson_L10 小时前
Python `Annotated` 与 LangGraph Reducer 学习笔记
python
韩师傅10 小时前
海天线算法的前世今生
python·计算机视觉
韩师傅10 小时前
当你的甲方设备过烂,要如何快速出效果?
python·计算机视觉
Warson_L10 小时前
LangGraph的MessageState and HumanMessage
python