Home > Mobile >  How Django evaluates object managers when we have multiple ones?
How Django evaluates object managers when we have multiple ones?

Time:11-02

Consider the following objects in Django ORM:

class Post(models.Model):
   ...
   published = PublishedPostManager()
   objects = models.Manager()

Now in the Django admin, only the published ones are shown. Could we change the behavior, so the Django ORM uses objects by default without any order?

CodePudding user response:

As described in the docs:

If you use custom Manager objects, take note that the first Manager Django encounters (in the order in which they’re defined in the model) has a special status. Django interprets the first Manager defined in a class as the “default” Manager

So to use objects by default, put it before published:

class Post(models.Model):
    ...
    objects = models.Manager()
    published = PublishedPostManager()

or define it as the default manager in the model Meta:

class Post(models.Model):
    ...
    published = PublishedPostManager()
    objects = models.Manager()

    class Meta:
        default_manager_name = 'objects'
  • Related