DEV Community

Cover image for Understanding Django Managers: The Gateway to Your Data
Ezeana Micheal
Ezeana Micheal

Posted on

Understanding Django Managers: The Gateway to Your Data

When working with Django models, you’re not just defining tables, you’re also defining how to interact with them. In this article, we’re going to use one of Django’s powerful tools when making queries, which is Django managers. Django managers define the interface for the interaction between your code and the database. The default one most are used to is the “objects” as in “students.objects.all()”.

Examples;

class Student(models.Model):  
    name = models.CharField(max_length=100)  
    age = models.PositiveIntegerField()

# Using the default manager  
all_students = Student.objects.all()  
adults = Student.objects.filter(age__gte=18)  
Enter fullscreen mode Exit fullscreen mode

Creating a Custom Manager

Alongside this default manager, we can also create custom managers. But why would we need to do so?

While objects is useful when performing basic queries, when dealing with larger projects, custom managers give user-defined reusable logic in code. Let's look at a practical example of this by using Django’s models. We then define a class that inherits from it and overwrites the get_queryset method in the student manager.

class ActiveStudentManager(models.Manager):  
    def get_queryset(self):  
        return super().get_queryset().filter(is_active=True)

class Student(models.Model):  
    name = models.CharField(max_length=100)  
    is_active = models.BooleanField(default=True)

    objects = models.Manager()        # Default manager  
    active = ActiveStudentManager()   # Custom manager  
Enter fullscreen mode Exit fullscreen mode

How then do you use this custom manager? Look below,

Student.objects.all()   # returns all students  
Student.active.all()    # returns only active students  
Enter fullscreen mode Exit fullscreen mode

Adding Custom Methods to Managers

You can also add methods to model managers to perform specific actions or queries. An example is sorting students by age group.

class StudentManager(models.Manager):  
    def teenagers(self):  
        return self.filter(age__gte=13, age__lte=19)

    def adults(self):  
        return self.filter(age__gte=18)

class Student(models.Model):  
    name = models.CharField(max_length=100)  
    age = models.PositiveIntegerField()

    objects = StudentManager()  
Enter fullscreen mode Exit fullscreen mode

Then using,

Student.objects.teenagers()  # all students aged 13–19  
Student.objects.adults()     # all students aged 18+  
Enter fullscreen mode Exit fullscreen mode

Multiple Managers in a Model

As seen in the first example, you can add more than 1 manager to a model to ease and streamline usage.

class ActiveStudentManager(models.Manager):  
    def get_queryset(self):  
        return super().get_queryset().filter(is_active=True)

class Student(models.Model):  
    name = models.CharField(max_length=100)  
    is_active = models.BooleanField(default=True)

    objects = models.Manager()        # Default manager  
    active = ActiveStudentManager()   # Custom manager  
Enter fullscreen mode Exit fullscreen mode

Managers vs. QuerySets

Managers are not qureysets. Managers are entry points to the database while QuerySets represent the actual collection of records. In the next article, we’ll see how we can use Querysets.

Multiple Managers in a Model

A model can have multiple managers, but they have one default manager, which is the objects; this can be subject to change, though.

class Student(models.Model):  
    name = models.CharField(max_length=100)  
    is_active = models.BooleanField(default=True)

    objects = models.Manager()       # default  
    active = ActiveStudentManager()  # custom  
Enter fullscreen mode Exit fullscreen mode

NOTE: The default manager is used in admin and migrations, so always keep objects = models.Manager() unless you know what you’re doing.

We have seen how Django managers can be used in this article, and how they help in holding some business logic and reusable queries. In the next article, we will explore querysets in Django and how they are used alongside this.

Top comments (0)