Django Managers
What is a Manager?
Django models have a Manager that is used to query the database. The Manager is the interface through which database query operations are provided to Django models.
How to setup a Manager?
To create a custom manager, you need to subclass models.Manager
and add your custom methods. Here is an example:
yourpp/mangers.py
python
from django.db.models import Manager
class CustomManager(Manager):
def get_queryset(self):
return super().get_queryset().filter(is_active=True)
yourpp/models.py
python
from django.db import models
from yourapp.managers import CustomManager
class YourModel(models.Model):
objects = CustomManager()
name = models.CharField(max_length=100)
is_active = models.BooleanField(default=True)
With graphene ?
If you are using graphene, you can use the DjangoObjectType
from graphene-django
to use your custom manager.
yourapp/schema/object_types.py
python
from graphene_django import DjangoObjectType
from yourapp.models import YourModel
from yourapp.managers import CustomManager
class YourModelType(DjangoObjectType):
class Meta:
model = YourModel
fields = "__all__"
@classmethod
def get_queryset(cls, queryset: CustomManager, info):
return queryset.get_queryset_from_request(info.context)