The use of the manager method in a Python-detailed Django framework

Source: Internet
Author: User
In statement Book.objects.all (), objects is a special property that needs to be queried through the database. In the 5th chapter, we just briefly say that this is the module manager. It's time to get a deep understanding of what managers is and how it's used.

In summary, the module manager is an object that the Django module uses to query the database. Each Django module has at least one manager, and you can create a custom manager to customize database access.

Here are two reasons you created a custom manager: Add an additional manager method, and/or repair the initial Queryset returned by the manager.
Add an additional Manager method

Adding an additional manager method is the preferred way to add table-level functionality to the module.

For example, we define a Title_count () method for the book model, which requires a keyword that returns the number of books containing the keyword. (This example is a bit farfetched, but it can explain how managers works.) )

# 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 now do this:

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

Here are some of the places that you should code this note:

    • We have established a Bookmanager class, which inherits the Django.db.models.Manager. This class has only one Title_count () method, which is used to make statistics. Note that this method uses Self.filter (), where self refers to the manager itself.
    • We assign the Bookmanager () value to the objects property of the model. It will replace the model's default manager (objects) if we do not specifically define it, it will be created automatically. We named it objects, which is to be consistent with the auto-created manager.

Why do we add a Title_count () method? is to encapsulate frequently used queries so that we don't have to repeat the code.
Modify the initial manager querysets

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

We can override the manager's basic queryset by overriding the Manager.get_query_set () method. Get_query_set () return a queryset according to your request.

For example, the following model has * two * manager. One returns all pairs of images, and the other only returns the book that the author is 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 hooks 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 the books in the database, and Book.dahl_objects.all () returns only one copy. Note that we explicitly set objects as an instance of manager, because if we do not do so, the only available manager will be dah1_objects.

Of course, since Get_query_set () returns a Queryset object, we can use the filter (), exclude (), and all the other Queryset methods. Like 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 techniques: using multiple managers in the same model. You can add multiple manager () instances to your model as long as you want. This is a simple way 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 results you want.

If you use a custom Manager object, be aware that the first manager that Django encounters (whichever is defined in the model) has a special status. Django will define the first manager as the default manager, and many parts of Django (but not the admin app) will explicitly use the manager for the model. The conclusion is that you should be careful to choose your default manager. Because the overlay get_query_set (), you may receive a useless return to the image, 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.