Django framework ORM Operation Details

Source: Internet
Author: User
Directory 1.1.1 generate query 1.1.2 create object 1.1.3 save modified object 1.1.4 save ForeignKey and ManyToManyField 1.1.5 search object 1.1.6 search all objects 1.1.7 filter search specific object 1.1.8 link filter 1.1.9 filter result set is unique 1.2.1 The result set is delayed. 1.2.2 Other QuerySe

Directory 1.1.1 generate query 1.1.2 create object 1.1.3 save modified object 1.1.4 save ForeignKey and ManyToManyField 1.1.5 search object 1.1.6 search all objects 1.1.7 filter search specific object 1.1.8 link filter 1.1.9 filter result set is unique 1.2.1 The result set is delayed. 1.2.2 Other QuerySe

Directory
1.1.1 generate Query
1.1.2 create an object
1.1.3 Save the modified object
1.1.4 Save the ForeignKey and ManyToManyField Fields
1.1.5 search object
1.1.6 retrieve all objects
1.1.7 filter and retrieve specific objects
1.1.8 link Filtering
1.1.9 the result set is unique.
1.2.1 The result set is delayed
1.2.2 Other QuerySet Methods
1.2.3 restrict QuerySets
1.2.4 field search
1.2.5 cross-link query
1.2.6 for filters, refer to model fields.
1.2.7 cache query set
1.2.8 comparison object
1.2.9 delete an object
1.3.1 modify multiple objects at a time
1.3.2 link object
1.3.3 One-to-One relationship
1.3.4 sequence-to-sequence relationship
1.3.5 One-to-one relationship

1.1.1 generate Query
After you create a data model, django will automatically provide you with an abstract database API to create, retrieve, modify, and delete objects. This document describes how to use APIs.

We refer to the following model, a weblog:

class Blog(models.Model):    name = models.CharField(max_length=100)    tagline = models.TextField()    def __unicode__(self):        return self.nameclass Author(models.Model):    name = models.CharField(max_length=50)    email = models.EmailField()    def __unicode__(self):        return self.nameclass Entry(models.Model):    blog = models.ForeignKey(Blog)    headline = models.CharField(max_length=255)    body_text = models.TextField()    pub_date = models.DateTimeField()    authors = models.ManyToManyField(Author)    n_comments = models.IntegerField()    n_pingbacks = models.IntegerField()    rating = models.IntegerField()    def __unicode__(self):        return self.headline

1.1.2 create an object

Describe the data of a database table using a python object. django uses an intuitive system, a model class to describe a data table, and a class instance to describe a detailed record of the table. Use the save () method of the model to create an object to the database.

From mysite. blog. models import Blog

B = Blog (name = 'Beatles Blog ', tagline = 'all the latest Beatles news .')
B. save ()
Django executes SQL statements to write objects to the database only when the save method is executed.

1.1.3 Save the modified object

Save the changes and still use the save () method.

B5.name = 'new name'
B5.save ()

1.1.4 Save the ForeignKey and ManyToManyField Fields

Cheese_blog = Blog. objects. get (name = "Cheddar Talk") entry. blog = cheese_blog # Add a record entry for ManyToManyField. save () joe = Author. objects. create (name = "Joe") entry. authors. add (joe) # add records for ForeignKey

1.1.5 search object
Retrieving objects from a database allows you to create a QuerySet through the Manage of the model. A QuerySet is a combination of objects in a database. It can have 0 or more filter conditions, in SQL, QuerySet is equivalent to a select statement that uses where or limit for filtering. You can get QuerySet by Manage of the model. Each model has at least one Manage.

1.1.6 retrieve all objects

The simplest way to retrieve all data in a table is to use all ().

All_entries = Entry. objects. all ()

1.1.7 filter and retrieve specific objects

Two methods are available to filter specific query results.
Filter (** kwargs) returns a new QuerySet that matches the query parameters.
Exclude (** kwargs) returns a new QuerySet that does not match the query parameters.

Entry. objects. filter (pub_date _ year = 2006)

1.1.8 link Filtering

Entry. objects. filter (headline _ startswith = 'wh ')
. Exclude (pub_date _ gte = datetime. now ())
. Filter (pub_date _ gte = datetime (2005, 1, 1 ))

1.1.9 the result set is unique.

Each time you complete a QuerySet, you get a brand new result set, excluding the previous one. Each completed result set can be stored, used, or reused.
Q1 = Entry. objects. filter (headline _ startswith = "What ")
Q2 = q1.exclude (pub_date _ gte = datetime. now ())
Q3 = q1.filter (pub_date _ gte = datetime. now ())
The three QuerySets are separated. The first is the result set whose headline starts with the word "What", and the second is the first subset, that is, the pub_date value is not greater than the current one, the third is the first subset, and pub_date is greater than the current one.

1.2.1 The result set is delayed

QuerySets are delayed. Creating QuerySets does not touch database operations. You can combine multiple filters until django starts to query the values. For example:

Q = Entry. objects. filter (headline _ startswith = "What ")
Q = q. filter (pub_date _ lte = datetime. now ())
Q = q. exclude (body_text _ icontains = "food ")
Print q
Although it seems that three filtering conditions are executed, django only starts to query and execute SQL statements to the database when print q is executed.

1.2.2 Other QuerySet Methods
In most cases, you use all (), filter (), and exclude ()

1.2.3 restrict QuerySets

Use the array limit Syntax of python to limit QuerySet, for example:
Obtain the first five

Entry. objects. all () [: 5]

Take the fifth to tenth

Entry. objects. all () [5: 10]

In general, the QuerySet is limited to return a new QuerySet, and the query is not evaluated immediately, unless you use the "step" parameter

Entry. objects. all () [: 10: 2]
Entry. objects. order_by ('headline') [0]
Entry. objects. order_by ('headline') [0: 1]. get ()

Sort query results
Entry. objects. all (). order_by ('first ')

1.2.4 field search

Field search specifies the WHERE Condition Clause of an SQL statement. query keywords are specified using the QuerySet method filter (), exclude (), and get.
Basic query field _ lookuptype = value
For example:

Entry. objects. filter (pub_date _ lte = '2017-01-01 ′)
Convert to SQL:

SELECT * FROM blog_entry WHERE pub_date <= '2017-01-01 ';
If you pass an invalid parameter, an exception is thrown.

Database APIs support some query types. Try the following:
A. exact

Entry. objects. get (headline _ exact = "Man bites dog ")
Equivalent

SELECT... WHERE headline = 'man bites dog ';
If the query does not provide double underscores, the default _ exact =

Blog. objects. get (id _ exact = 14) # Explicit form
Blog. objects. get (id = 14) # _ exact is implied
B. iexact -- case insensitive

Blog. objects. get (name _ iexact = "beatles blog ")
The blog title matches "Beatles Blog", "beatles blog", and even "BeAtlES blOG ".

C. contains-including queries, case sensitive

Entry. objects. get (headline _ contains = 'lennon ')
Convert to SQL

SELECT... WHERE headline LIKE '% Lennon % ';
Icontains are case insensitive

Startswith, endswith, istartswith, iendswith
Prefix fuzzy match and suffix fuzzy match

1.2.5 cross-link query
Entry. objects. filter (blog _ name _ exact = 'Beatles Blog ')
This can span the depth you want.

Reverse cross-link query

Blog. objects. filter (entry _ headline _ contains = 'lennon ')

If a multi-level link query is performed, the intermediate model has no value, and django is treated as null without exception.

Blog. objects. filter (entry _ author _ name = 'lennon ');
Blog. objects. filter (entry _ author _ name _ isnull = True );
Blog. objects. filter (
Entry _ author _ isnull = False,
Entry _ author _ name _ isnull = True );

1.2.6 for filters, refer to model fields.

In the current example, we have set up a filter to compare the model field value with a fixed value. However, if we want to compare the values of one index and other fields in the same model, django provides F () -- Special Operation for getting a column value of an object

From django. db. models import F
Entry. objects. filter (n_pingbacks _ lt = F ('n' _ comments '))
Note: n_pingbacks and n_comments are model Entry attributes.

Django supports addition, subtraction, multiplication, division, and modulo computing.

Entry. objects. filter (n_pingbacks _ lt = F ('n' _ comments ') * 2)
Entry. objects. filter (rating _ lt = F ('n' _ comments ') + F ('n' _ pingbacks '))
Entry. objects. filter (author _ name = F ('blog _ name '))

Primary Key query shortcuts

Blog. objects. get (id _ exact = 14) # Explicit form
Blog. objects. get (id = 14) # _ exact is implied
Blog. objects. get (pk = 14) # pk implies id _ exact

Not limited to _ exact queries

# Get blogs entries with id 1, 4 and 7
Blog. objects. filter (pk _ in = [1, 4, 7])

# Get all blog entries with id> 14
Blog. objects. filter (pk _ gt = 14)

Cross-Query

Entry. objects. filter (blog _ id _ exact = 3) # Explicit form
Entry. objects. filter (blog _ id = 3) # _ exact is implied
Entry. objects. filter (blog _ pk = 3) # _ pk implies _ id _ exact

Like statement escape percentage

Entry. objects. filter (headline _ contains = '% ')
Escape

SELECT... WHERE headline LIKE '% \ % ';

1.2.7 cache query set

Each QuerySet contains a cache to minimize access to the database. It is very important to understand how he works. He can write the most efficient code.
In the newly created QuerySet, the cache is empty. The value of QuerySet is set for the first time. Therefore, when a database query occurs, django caches the query results and returns them to the request. The subsequent query values reuse the cached results.

Keep the habit of caching, because it will be troublesome if you do not use the query cache correctly. For example, the following example creates two querysets.

Print [e. headline for e in Entry. objects. all ()]
Print [e. pub_date for e in Entry. objects. all ()]
This means that the database query will be executed twice, and the actual two databases will be loaded.

To avoid this problem, you can simply save QuerySet for reuse.

Queryset = Poll. objects. all ()
Print [p. headline for p in queryset] # Evaluate the query set.
Print [p. pub_date for p in queryset] # Re-use the cache from the evaluation.

1.2.8 comparison object

Compare two model instances, using the python standard operator, two equal signs =

Some_entry = other_entry
Some_entry.id = other_entry.id
Some_obj = other_obj
Some_obj.name = other_obj.name

1.2.9 delete an object

The delete method is very convenient. The method name is delete (). This method directly deletes an object without returning a value.

E. delete ()
You can also delete objects in batches. Each QuerySet has a delete () method to delete all objects in the QuerySet.

1.3.1 modify multiple objects at a time

Sometimes you want to assign a specific value to a field of all objects in QuerySet, you can use the update () method.
For example:

# Update all the headlines with pub_date in 2007.
Entry. objects. filter (pub_date _ year = 2007). update (headline = 'everything is the same ')

This method can only be used for non-correlated fields and Foreign keys.

B = Blog. objects. get (pk = 1)
# Change every Entry so that it belongs to this Blog.
Entry. objects. all (). update (blog = B)

The update () method does not return any value, and QuerySet does not support the save method. To execute save, you can:

For item in my_queryset:
Item. save ()

Update can also use F ()

# This will raise a FieldError
Entry. objects. update (headline = F ('blog _ name '))

1.3.2 link object

When you define a link in the model, the model instance has a convenient API to access the link object. Take the model above this page for example, an Entry
Object To obtain the blog object and access the blog attribute e. blog.
Django also creates an API to access the other side of the relational object. A blog object accesses the Entry list B. entry_set.all ().

1.3.3 One-to-One relationship

If an object has a ForeignKey, this model instance accesses the relational object through simple attributes.

E = Entry. objects. get (id = 2)
E. blog # Returns the related Blog object.
You can use the foreign key attribute to obtain and assign values. If you modify the foreign key value, the save () method is executed before it is saved to the database.

E = Entry. objects. get (id = 2)
E. blog = some_blog
E. save ()
If ForeignKey is set to null = True, You can assign a value to None.

E = Entry. objects. get (id = 2)
Print e. blog # Hits the database to retrieve the associated Blog.
Print e. blog # will not be retrieved from the database; Use the cached value.

E = Entry. objects. select_related (). get (id = 2)
Print e. blog # will not be retrieved from the database; Use the cached value.
Print e. blog # will not be retrieved from the database; Use the cached value.

B = Blog. objects. get (id = 1)
B. entry_set.all () # Return the associated objects of all blogs.

# B. entry_set is a Manager that returns QuerySets.
B. entry_set.filter (headline _ contains = 'lennon ')
B. entry_set.count ()

B = Blog. objects. get (id = 1)
B. entries. all () # Return the associated objects of all blogs.

# B. entries is a Manager that returns QuerySets.
B. entries. filter (headline _ contains = 'lennon ')
B. entries. count ()

Add (obj1, obj2 ,...) Add multiple relational objects
Create (** kwargs) to create a new object
Remove (obj1, obj2 ,...) Remove multiple relational objects
Clear () clears all relational objects

B = Blog. objects. get (id = 1)
B. entry_set = [e1, e2]

1.3.4 sequence-to-sequence relationship

E = Entry. objects. get (id = 3)
E. authors. all () # return all authors of the Entry.
E. authors. count ()
E. authors. filter (name _ contains = 'john ')

A = Author. objects. get (id = 5)
A. entry_set.all () # return all Author entries.

1.3.5 One-to-one relationship

Class EntryDetail (models. Model ):
Entry = models. OneToOneField (Entry)
Details = models. TextField ()

Ed = EntryDetail. objects. get (id = 2)
Ed. entry # Return the Entry object.

Supplement:
Manage. py functions and model-related commands
Syncdb creates data tables required by all applications
SQL display CREATE TABLE call
Sqlall initializes data loading statements from SQL files like the preceding SQL statements.
Sqlindexes displays the call to create an index for the primary key
Sqlclear: Call to display DROP TABLE
Sqlresetsqlclear and SQL combination
Sqlcustom displays the custom SQL statements in the specified SQL File
Loaddata loads initial data (similar to sqlcustom, but there is no original SQL)
Dmpdata outputs the data in the existing database as jason, in xml format.

Query related methods
All returns a QuerySet of all data records in the include mode.
Filter returns a QuerySet containing model records that meet the specified conditions.
The opposite of exclude and filter is used to find records that do not meet the conditions.
Get gets a single qualified record. If no or more records are found, an exception is thrown.

Use Extra to adjust SQL statements

Original article address: Django framework ORM operation details, thanks to the original author for sharing.

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.