Django 11 Model Managers
Django 11 Model Managers
Hence, there exists at least one manager for every model in a django
application.
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}'
objects = PersonManager()
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()
class Meta:
default_manager_name = ‘persons’
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.
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.