Django Model managers and properties
A model is the single, definitive source of data about your data. It contains the essential fields and behaviours of the data you’re storing. Generally, each model maps to a single database table. And an instance of that class represents a particular record in the database table.
1. Each model(database table) is a Python class that sub classes django.db.models.Model.
2. Each attribute of the model represents a database field(column).
from django.db import modelsclass User(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField() def __str__(self):
To create an object, instantiate it using keyword arguments to the model class, then call save() to save it to the database.
Assume models are in a file project1/app1/models.py
from app1.models import Useruser = User(name="xxx", email="email@example.com")
To create and save an object in a single step, use the create() method.
from app1.models import Useruser = User.objects.create(name="xxx", email="firstname.lastname@example.org")
A Manager is the interface through which database query operations are provided to Django models. By default, Django adds a Manager with the name “objects” to every Django model class.
from django.db.models import Model, Managerclass User(Model):
objects = Manager() # The default Manager.
User.objects.all() # This returns a list of users.
Objects is a special attribute through which you query your database. We briefly identified this as the model’s manager, and it’s an instance of the class django.db.models.Manager; it’s where all the default methods for performing queries against the entire model class — all(), get(), filter(), etc.
A model’s manager is an object through which Django models perform database queries. Each Django model has at least one manager, and you can create custom managers in order to customise database access.
Adding extra manager methods(custom managers) is the preferred way to add “table-level” functionality to your models whereas for “row-level” functionality use model methods.
For example, let’s give our Book model a manager method title_count() that takes a keyword and returns the number of books that have a title containing that keyword.
from django.db import modelsclass BookManager(models.Manager):
def title_count(self, keyword):
return self.filter(title__icontains=keyword).count()class Book(models.Model):
title = models.CharField(max_length=100)
publication_date = models.DateField()
num_pages = models.IntegerField(blank=True, null=True) objects = BookManager() # The Custom Manager. def __unicode__(self):
With this manager, we can now do this:
Book.objects.title_count(‘django’) # This will return number of books that have a title containing django.
Note that the method uses self.filter(), where self refers to the manager itself.
Define custom methods on a model to add “row-level” functionality to your objects.
Here’s a model with a few custom methods:
from django.db import modelsclass Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50) def _get_full_name(self):
return '%s %s' % (self.first_name, self.last_name) # Returns the person's full name. full_name = property(_get_full_name)
person = Person.objects.get(first_name='xyz', last_name='abc')person.full_name # Note this isn't a method -- it's treated as an attribute, It returns 'xyz abc'
The method in this example is a “property.” Properties are a neat way to implement attributes whose usage resembles attribute access, but whose implementation uses method calls. These are sometimes known as “managed attributes”.