Django notes-Models

Source: Internet
Author: User

The models example is as follows. This document describes the examples.
From Django. DB import models

# Create your models here.
Class publisher (models. Model ):
Name = models. charfield (max_length = 30)
Address = models. charfield (max_length = 50)
City = models. charfield (max_length = 60)
State_province = models. charfield (max_length = 30)
Country = models. charfield (max_length = 50)
Website = models. urlfield ()
 
Def _ Unicode _ (Self ):
Return "Name: % s, address: % s" % (self. Name, self. Address)
 
Class author (models. Model ):
First_name = models. charfield (max_length = 30)
Last_name = models. charfield (max_length = 40)
Email = models. emailfield (blank = true)
 
Def _ Unicode _ (Self ):
Return self. last_name
 
Class book (models. Model ):
Tille = models. charfield (max_length = 100)
Authors = models. manytomanyfield (author)
Publisher = models. foreignkey (publisher)
Publication_date = models. datefield ()
 
Def _ Unicode _ (Self ):
Return self. tille

 

1. Basic operations
From website. app import models

1) insert
P1 = models. Publisher (name = 'apress', address = '1970 Telegraph Avenue ',
City = 'berkeley ', state_province = 'CA', Country = 'U. S. .',
Website = 'HTTP: // www.apress.com /')
P1.save ()

2) Select
Publisher_list = models. publisher. Objects. All ()
Publisher_no.1 = models. publisher. Objects. All () [0: 2]

3) Update
P = models. publisher. Objects. All () [0] # retrieve the pointer of the first record
P. Name = "Hongxing" # change the name to Hongxing
P. Save () # Save

4) Filter
Models. publisher. Objects. Filter (name = 'hongxing ') # single-condition search
Models. publisher. Objects. Filter (name = "chubanshe", city = 'beijing') # And Condition
Mdoels. publisher. Objects. Filter (name = 'hognx'). Update (city = 'zaozhuang ')

5) Like
Models. publisher. Objects. Filter (name _ contains = 'Hong ') # All records whose names contain Hong

6) retrieving single objects
Models. publisher. Objects. Get (name = "Hongxing ")

7) Order
Models. publisher. Objects. order_by ('name ')
Models. publisher. Objects. order_by ('name', 'city ')
Models. publisher. Objects. order_by ('-name') # Reverse Order

Specify the default sorting method:
Class publisher (models. Model ):
Name = models. charfield (max_length = 30)
Address = models. charfield (max_length = 50)
City = models. charfield (max_length = 60)
State_province = models. charfield (max_length = 30)
Country = models. charfield (max_length = 50)
Website = models. urlfield ()

Def _ Unicode _ (Self ):
Return self. Name

Class meta:
Ordering = ['name']

8) chaining lookups
Mdoels. publisher. Objects. Filter ('name'). order_by ('city ')

9) Delete
Models. publisher. Objects. Get (name = 'hognxing '). Delete ()

 

2. Foreign key

1) foreignkey is used to define the multi-to-one relationship. The foreignkey parameter is a primary key class, just as in the beginning of this article.
For example, the foreignkey parameter of book. publisher is the publisher class.

2) objects can also be associated with themselves, using mdels. foreignkey ('self ') to establish a recursive relationship.

3) 2) use a string. Yes, the foreign key parameter can be a string. This is not yet defined in the parameter class.
Especially applicable. For example, if the publisher class is not defined, you can use models. foreignkey ('her her ')
Note: Only string references can be applied to models in the same models. py file. Other or imported models are unavailable.

4) Access
As shown in the models provided at the beginning of the article, the book has a foreign key publisher.
As shown in the following code, accessing publisher through the book object is no different from accessing a normal field.
However, when you access the book through the primary key publisher, you need to use the book_set form.
That is, the lower case + _ set of the model class name in the primary key

>>> From website. Books Import Models
>>> B = models. Book. Objects. Get (tille = 'djangobook ')
>>> P = models. publisher. Objects. Filter (name = 'apress') [0]
>>> B. Publisher
<Publisher: Name: apress, address: 2855 Telegraph Avenue>
>>> P. book_set.all ()
[<Book: djangobook>, <book: pythonbook>]
 
3. manytoyun
1) in which model does manytomanyfield be placed?
The example given at the beginning of the analysis article: an author can write more books and one book can have more books.
This field can be stored in book or author. But not both.

2) Self-Association and string parameters are the same as foreignkey.

3) Access is similar to foreignkey
Here is a description. The book_set attribute must be a record of author, not queryset.

Forward access:
>>> Book = models. Book. Objects. Get (tille = 'djangobook ')
>>> Book. Authors. All ()
[<Author: yonggao>, <Author: xiuqi>]
Reverse access:
>>> Aut = models. Author. Objects. Filter (last_name _ contains = 'yonggao ')
>>> Aut. book_set.all ()
Traceback (most recent call last ):
File "<Console>", line 1, in <module>
Attributeerror: 'queryset' object has no attribute 'book _ set'
>>>
>>> Aut = Aut [0]
>>> Aut. book_set.all ()
[<Book: djangobook>, <book: pythonbook>]
 
4. Modify the database model
After the database is created, if you add or delete columns, Python manage. py syncdb does not work.
This section describes how to modify Database columns.
1) Django synchronizes models and database. It is better to directly reference the original text here:
■ Django will complain loudly if a model contains a field that has not yet been created in
Database table. This will cause an error the first time you use the Django database API to query
The given table (I. e., it will happen at code execution time, not at Compilation Time ).
■ Django does not care if a database table contains columns that are not defined in the model.
■ Django does not care if a database contains a table that is not represented by a model.

2) Change Field
When adding a field, you can add the content to be added to models. py.
Then, use Python manage. py sqlall books to view the database creation in the books app.
In this way, you can easily use the alter command to modify your database according to the SQL statement.

5. Managers
In book. Objects. All (), objetcs is an example of a manager. So when do I need it?
Customize your own manager: to add extra manager methods, and/or
To modify the initial queryset the manager returns.

1) adding extra manager Methods
Example:
Add a method for counting the number of specified keywords to the book model.

Class bookmanager (models. Manager ):
Def title_count (self, keyword ):
Return self. Filter (tille _ icontains = keyword). Count ()

Class book (models. Model ):
Tille = models. charfield (max_length = 100)
Authors = models. manytomanyfield (author)
Publisher = models. foreignkey (publisher)
Publication_date = models. datefield ()
Objects = bookmanager ()
 
Def _ Unicode _ (Self ):
Return self. tille

2) modifying initial Manager querysets
The default queryset of the manager returns all records in the table. If necessary, you can customize the returned content.
You only need to override manager. get_query_set.
Example: If the following model uses the Dahl manager, when using book. dahl_ojbects.all (),
Only all books written by yonggao are returned.

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 = 'yonggao ')

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

Note:
When you define your own manager, always keep the default manager models. Manager.

The custom manager can be used to define a common filter. For example, the following example uses different
It is easier for managers to manage different data.

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 ()

NOTE: If multiple managers are defined in the model, the first manager is Django's default
Manager. Many parts of Django use the default manager to process the model.

 

6. Executing raw SQL queries
You can use standard Python database statements in Django.

In addition, we recommend that you place SQL statemets in the model methods active manager methods.
Example:
From Django. DB import connection, Models

Class personmanager (models. Manager ):
Def first_names (self, last_name ):
Cursor = connection. cursor ()
Cursor.exe cute ("""
Select distinct first_name
From people_person
Where last_name = % s ", [last_name])
Return [row [0] For row in cursor. fetchone ()]

Class person (models. Model ):
First_name = models. charfield (max_length = 50)
Last_name = models. charfield (max_length = 50)
Objects = personmanager ()

 <End of this section>

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.