简体   繁体   中英

How django add objects attribute to model classes?

As in the Django documentation

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

How does Django add an attribute to model classes? Whether it is inherited from the models.Model or Django add objects=models.Manager() dynamically to each model?

It's added dynamically to each model class unless you add one yourself.

Have a look at 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM