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

时间:2018-04-04 07:03:50

标签: python django django-models django-queryset django-managers

与Django文档中一样

  

默认情况下,Django为每个Django模型类添加一个名为 objects 的Manager

Django如何为模型类添加属性? 它是继承自models.Model还是Django动态添加objects=models.Manager()到每个模型?

1 个答案:

答案 0 :(得分:0)

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

查看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)