0% found this document useful (0 votes)
86 views4 pages

Django 11 Model Managers

Managers provide an interface for interacting with database query operations in Django models. There is at least one manager for every model that retrieves all objects by default. Custom managers can be created to add extra methods or modify the initial queryset. Managers allow writing reusable common query code for models in a clean, efficient, and maintainable way following the DRY principle.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
86 views4 pages

Django 11 Model Managers

Managers provide an interface for interacting with database query operations in Django models. There is at least one manager for every model that retrieves all objects by default. Custom managers can be created to add extra methods or modify the initial queryset. Managers allow writing reusable common query code for models in a clean, efficient, and maintainable way following the DRY principle.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

Django 11: Django Model Managers

A manager is an interface through which database query operations


are provided to Django models. At least one Manager exists for every
model in a Django application, objects is the default manager of every
model that retrieves all objects in the database.
A manager is an interface through which database query operations are
provided to django models. It is some kind of ‘gate’ between application
and database.

Hence,  there exists at least one manager for every model in a django
application.

Creating Custom Model Managers

As we know objects is the default model manager for every model,


therefore Post.objects.all() will return all post objects.
The objects method is capable of doing all basic QuerySets then why
would we need a custom model manager?
There are two reasons you might want to customize a Manager –

 To add extra Manager methods.


 To modify the initial QuerySet the Manager returns.
Let’s create a model manager to retrieve all the published posts.

Using the objects manager published posts can be retrieved with the


following query.
Benefits of using managers in your code:

1. Clean code.
2. Efficient code.
3. Maintainable code.
4. Writing common query code for the model which are reusable. (DRY
rule i.e. Don’t repeat yourself)

class Person(models.Model):
    GENDER = (
        ('M', 'Male'),
        ('F', 'Female'),
    )
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    email = models.EmailField(unique = True,null=True)
    gender = models.CharField(max_length=1, choices= GENDER,default='N/A')

#will add our manager here

    class Meta:
        verbose_name_plural = 'All Persons'

    @property
    def full_name(self):
        return f'{self.first_name} {self.last_name}'

    def __str__(self):
        return f'{self.first_name} {self.last_name}'

All Persons Data


#will add our manager here

objects = PersonManager()

>>> from first_app.models import Person


>>> Person.persons.all()
<QuerySet [<Person: Inayra Mutahharah>, <Person: Zaira Anaya>, <Person: Zahra Ibnat>, <Person:
Jon Doe>, <Person: Yeasir Arafat>, <Person: Arafat Yeasir>]>
>>> Person.persons.all().count()
6

class PersonManager(models.Manager):
    def male_persons(self):
        return self.filter(gender='M')
      
    def female_persons(self):
        return self.filter(gender='F')

    def total_persons(self):
        return self.all().count()

>>> from first_app.models import Person


>>> males = Person.objects.male_persons()
>>> males
<QuerySet [<Person: Jon Doe>, <Person: Yeasir Arafat>, <Person: Arafat Yeasir>]>
>>> females = Person.objects.female_persons()
>>> females
<QuerySet [<Person: Inayra Mutahharah>, <Person: Zaira Anaya>, <Person: Zahra Ibnat>]>

class Meta:
default_manager_name = ‘persons’

What is a Model Manager?

For every model in Django, there is an associated manager which is an interface for interacting
with the database. To access the manager of a model, you simply need to use
the objects property on the model e.g. FootballTeam.objects, however, this property is
customisable.

If you wanted the manager property to be named teams, you would simply declare an attribute
named teams of type Manager within the model.

Why are Model Managers so important?

As mobile app developers, we should be writing clean, efficient, maintainable code and follow
the DRY (Don’t Repeat Yourself) software architecture principle. The django model managers
play a good part in ensuring you tick all of these boxes; being more vital for maintenance and
adhering to the DRY principle.

The reason it ticks these boxes is that it keeps the querying in your django application in a
centralised place; queries that your application perform come from one place instead of being
wrote on the fly in each View that requires the query.                     

You might also like