Describes how to use the Manager method in the Python Django framework.

Source: Internet
Author: User
This article describes how to use the Manager method in the Python Django framework, including modifying the initial ManagerQuerySets and adding additional Manager methods. For more information, see the statement Book. objects. in all (), objects is a special attribute and needs to be used to query the database. In chapter 2, we simply say that this is the module manager. Now it is time to learn more about what managers are and how to use them.

In short, module manager is an object through which the Django module queries the database. Each Django module has at least one manager. You can create a custom manager to customize database access.

The following are two reasons for creating a custom manager: adding an additional manager method and/or repairing the initial QuerySet returned by the manager.
Add additional Manager Methods

The additional manager method is the first choice to add table-level functions to the module.

For example, we have defined a title_count () method for the Book model. It requires a keyword to return the number of books containing this keyword. (This example is a little far-fetched, but it shows how managers work .)

# models.pyfrom django.db import models# ... Author and Publisher models here ...**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)  authors = models.ManyToManyField(Author)  publisher = models.ForeignKey(Publisher)  publication_date = models.DateField()  num_pages = models.IntegerField(blank=True, null=True)  **objects = BookManager()**  def __unicode__(self):    return self.title

With this manager, we can do this now:

>>> Book.objects.title_count('django')4>>> Book.objects.title_count('python')18

Here are some notes for coding:

  • We have created a BookManager class that inherits django. db. models. Manager. This class has only one title_count () method for statistics. Note that this method uses self. filter (), where self refers to the manager itself.
  • We assign BookManager () to the objects attribute of the model. It will replace the default manager (objects) of the model. If it is not specifically defined, it will be automatically created. We name it objects to be consistent with the automatically created manager.

Why do we need to add a title_count () method? To encapsulate frequently used queries, we do not need to recode them.
Modify initial Manager QuerySets

The basic QuerySet of manager returns all objects in the system. For example, ''book. objects. all () ''returns all books in the database Book.

We can override the Manager. get_query_set () method to override the basic QuerySet of the manager. Get_query_set () returns a QuerySet as required.

For example, the following model has two * managers. One returns all the objects, and the other returns only the books written by Roald Dahl.

from django.db import models**# First, define the Manager subclass.****class DahlBookManager(models.Manager):**  **def get_query_set(self):**    **return super(DahlBookManager, self).get_query_set().filter(author='Roald Dahl')****# Then hook it into the Book model explicitly.**class Book(models.Model):  title = models.CharField(max_length=100)  author = models.CharField(max_length=50)  # ...  **objects = models.Manager() # The default manager.**  **dahl_objects = DahlBookManager() # The Dahl-specific manager.**

In this example model, Book. objects. all () returns all books in the database, while Book. dahl_objects.all () returns only one copy. note that we explicitly set objects to the manager instance, because if we do not do this, the only available manager will be dah1_objects.

Of course, because get_query_set () returns a QuerySet object, we can use the filter (), exclude () and all other QuerySet methods. These syntaxes are correct:

Book.dahl_objects.all()Book.dahl_objects.filter(title='Matilda')Book.dahl_objects.count()

This example also points out other interesting technologies: using multiple managers in the same model. You can add multiple manager () Instances for your model as long as you want. This is a simple method to add a general filter to a model.

For example:

class MaleManager(models.Manager):  def get_query_set(self):    return super(MaleManager, self).get_query_set().filter(sex='M')class FemaleManager(models.Manager):  def get_query_set(self):    return super(FemaleManager, self).get_query_set().filter(sex='F')class Person(models.Model):  first_name = models.CharField(max_length=50)  last_name = models.CharField(max_length=50)  sex = models.CharField(max_length=1, choices=(('M', 'Male'), ('F', 'Female')))  people = models.Manager()  men = MaleManager()  women = FemaleManager()

This example allows you to execute ''person. men. all () '', ''person. women. all () '', ''person. people. all () ''query to generate the desired result.

If you use a custom Manager object, note that the first Manager encountered by Django (based on its location defined in the Model) has a special State. Django will define the first Manager as the default Manager. Many parts of Django (but not the admin application) will explicitly use this manager for the model. The conclusion is that you should carefully select your default manager. Because get_query_set () is overwritten, you may receive a useless response object. You must avoid this situation.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.