afi
afi

Reputation: 603

How to set custom model manager as a default model manager in Django?

I have multiple apps and models in Django project. Now i want to use custom model manager in all apps models. i don't want to write custom model manager query inside of every single model. I just want to know is that possible to set custom model manager as default models manager for all apps?

manager.py

class CustomQuerySet(models.Manager):
    def get_queryset(self):
        return super(CustomQuerySet, self).get_queryset().filter(status=True)

Upvotes: 2

Views: 2975

Answers (2)

yovel cohen
yovel cohen

Reputation: 267

You can set an abstract model and inherit it in all your models,

class MyProjectAbstractModel(models.Model):
   # regular common models fields here
   
   objects = models.Manager() # you can specify the built-in or not, for readbilty I like to do so, you can also set your manager to the objects attribute
   my_custom_manager = CustomQuerySet() # your manager
   class Meta:
      abstract = True # means migrations won't handle this model

class MyModelInAppOne(MyProjectAbstractModel):
   # your implementation... 

Upvotes: 2

Sheraram_Prajapat
Sheraram_Prajapat

Reputation: 597

You can create a custom manager like this and override the get_queryset method or you can add your own methods and filters.

class PublishedManager(models.Manager):
 def get_queryset(self):
 return super().get_queryset().filter(status='published')

class Post(models.Model):
 # ...
 objects = models.Manager() # The default manager.
 published = PublishedManager() # custom manager.

This custom(PublishedManager)manager will allow you to retrieve posts using Post.published.all(). This will give all the posts having status as published.

This allows you to have two managers objects, the default manager and published, the custom manager or you can override your default manager like this objects = PublishedManager()

Upvotes: 3

Related Questions