By continuing to navigate on this website, you accept the use of cookies to serve you more relevant services & content.
For more information and to change the setting of cookies on your computer, please read our Cookie Policy.

Django Model managers and properties

Model:

A model is the single, definitive source of data about your data. It contains the essential fields and behaviors 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 subclasses django.db.models.Model.

2. Each attribute of the model represents a database field(column).

Example:

from django.db import models

class User(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField()

    def __str__(self): 
        return self.name

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

Example:

from app1.models import User

user = User(name="xxx", email="xxx@xxx.xxx")
user.save()

To create and save an object in a single step, use the create() method.

Example:

from app1.models import User

user = User.objects.create(name="xxx", email="xxx@xxx.xxx")

Managers:

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.

Example: 

from django.db.models import Model, Manager

class User(Model):
        ....
        ....
        objects = Manager()   # The default Manager.

Usage:

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 customize database access.

Custom Managers:

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 models

class 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):
        return self.title

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.

Model methods: 

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 models

class 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)
    
    def __unicode__(self):
        return self.full_name

Usage:

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".

    Posted On
  • 06 February 2012
  • By
  • Micropyramid

Need any Help in your Project?Let's Talk

Latest Comments
Related Articles
Understanding Checkout flow in Django Oscar.

Explaining Django Oscar checkout flow.

Continue Reading...
How To Add A Custom Managers In Django

Django Custom Managers - A Manager is the interface through which database query operations are provided to Django models. At least one Manager exists for ...

Continue Reading...
How to create thumbnail image in Django templates using sorl-thumbnail?

Sorl thumbnail is the package which is being widely used to generate thumbnail in Django. It will create thumbnail of given size for the given ...

Continue Reading...
open source packages

Subscribe To our news letter

Subscribe and Stay Updated about our Webinars, news and articles on Django, Python, Machine Learning, Amazon Web Services, DevOps, Salesforce, ReactJS, AngularJS, React Native.
* We don't provide your email contact details to any third parties