Django Model managers and properties

Reading Time : ~ .

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

    By Posted On
SENIOR DEVELOPER at MICROPYRAMID

Need any Help in your Project?Let's Talk

Latest Comments
Related Articles
Django Conditional Expressions in Queries Anjaneyulu Batta

Reduce database queries in django with Conditional Expressions. By using Conditional Expressions we can use "If...Elif...Else" expressions while querying the database so that we can ...

Continue Reading...
How to Create initial django migrations for existing DB schema. Chaitanya Kattineni

Django provides the comfort database migrations from its version 1.8, with which we can avoid the usage of third party packages like south. Adding migrations ...

Continue Reading...
Using Sentry To Track Django live Events Jagadeesh V

Let us now learn how to track exceptions and events in SENTRY. We will setup browser and server end tracking for Django Project.

Continue Reading...

Subscribe To our news letter

Subscribe to our news letter to receive latest blog posts into your inbox. Please fill your email address in the below form.
*We don't provide your email contact details to any third parties