Django 如何将对象属性添加到模型 类?

How django add objects attribute to model classes?

如 Django 文档中所述

By default, Django adds a Manager with the name objects to every Django model class

Django 如何给模型添加属性类? 是否继承自models.ModelDjango动态添加objects=models.Manager()到每个模型?

除非您自己添加一个,否则它会动态添加到每个模型中class。

看看ModelBase._prepare:

def _prepare(cls):
    """Create some methods once self._meta has been populated."""
    opts = cls._meta
    opts._prepare(cls)

    ...

    if not opts.managers:
        if any(f.name == 'objects' for f in opts.fields):
            raise ValueError(
                "Model %s must specify a custom Manager, because it has a "
                "field named 'objects'." % cls.__name__
            )
        manager = Manager()
        manager.auto_created = True
        cls.add_to_class('objects', manager)