Django Book Learning notes-advanced in the model

Source: Internet
Author: User

1. Accessing the foreign key (Foreign key) value

When you get a field for the ForeignKey , you get the relevant data model object. For example:

>>> B = Book.objects.get (id=50) >>> b.publisher<publisher:apress publishing>>>> B.publisher.websiteu ' http://www.apress.com/'

For a relationship defined by ForeignKey, the other end of the relationship can be traced back in reverse, albeit slightly different because of the asymmetric relationship. From a Publisher object, get books directly, using Publisher.book_set.all (), as follows:

>>> p = Publisher.objects.get (name= ' Apress publishing ') >>> P.book_set.all () [<book:the Django Book>, <book:dive into Python>, ...]

In fact,Book_set is just a QuerySet, so it can be like QuerySet , which enables data filtering and slitting. The property name Book_set is made up of lowercase (such as book) plus _set of the model name.

2. Access to many-to-many values

Many-to-many and foreign keys work the same way, but we are dealing withQuerySetInstead of the model instance. For example:

>>> B = Book.objects.get (id=50) >>> b.authors.all () [<author:adrian holovaty>, <author: Jacob kaplan-moss>]>>> b.authors.filter (first_name= ' Adrian ') [<author:adrian holovaty>]>> > B.authors.filter (first_name= ' Adam ') []

The reverse is like using the foreignkey field.

3. Changing the database schema

We note that syncdb only creates data tables that are not yet in the database, does not synchronize your data model modifications, and does not handle deletions in the data model. If you add or modify a field in the data model, or delete a data model, you need to manually make the appropriate changes in the database yourself.

When dealing with model modifications, it is important to keep the workflow of the Django database layer in mind.

    • If the model contains a field that has not been established in the database, Django will report an error message. The first time you use the Django database API to request a table that does not exist can cause errors. (for example, it will fail at run time, not compile time)

    • Django does not care if the tables in the database have columns that are not defined in the model.

    • Django does not care if there are tables in the database that are not represented by the model.

4.Managers

1). Add the Additional Manager method

     added additional manager method is the preferred way to add table-level functionality to a module. For example, we define a Title_count () method for the book Model:

#&NBSP;MODELS.PYFROM&NBSP;DJANGO.DB&NBSP;IMPORT&NBSP;MODELS#&NBSP;  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 

2). Modify the initial manager querysets

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.

# models.pyfrom django.db import modelsclass dahlbookmanager (models. Manager):     def get_query_set (self):         Return super (dahlbookmanager,self). Get_query_set (). Filter (authors= ' 2 ')             #Roald  Dahl  id=2     query foreign keys, The Manytomany field appears to be only queried by ID 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 = models. Manager ()     dahl_objects = dahlbookmanager ()     def __ Unicode__ (self):         return self.title 

In this example model, Book.objects.all () returns all the books in the database, and Book.dahl_objects.all () returns only the data with the author ID 2

Django Book Learning notes-advanced in the model

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.