Django ORM Summary [reprint]

Source: Internet
Author: User
Tags new set

Django ORM Summary [reprint]

Reprint Address:

Http://www.cnblogs.com/linjiqin/archive/2014/07/01/3817954.html

Directory
1.1.1 Generating Queries
1.1.2 Creating objects
1.1.3 To save modified objects
1.1.4 Saving ForeignKey and Manytomanyfield fields
1.1.5 Retrieving objects
1.1.6 Retrieving all the objects
1.1.7 filtering to retrieve specific objects
1.1.8 Link filtering
1.1.9 Filter result set is the only
1.2.1 Result set is deferred
1.2.2 Other methods of Queryset
1.2.3 Limit Querysets
1.2.4 Field Lookup
1.2.5 Cross-Relationship query
1.2.6 filters refer to model fields
1.2.7 Cache Query Set
1.2.8 Comparing objects
1.2.9 deleting objects
1.3. Modify multiple Objects 11 times
1.3.2 Relationship Object
1.3.3 One-to-many Relationship
1.3.4 Many-to-many Relationship
1.3.5 One-to-one relationship


1.1.1 Generating Queries
Once you've created the data model, Django will automatically provide you with a database abstraction API that can create, retrieve, modify, and delete objects, and this document explains how to use the API.

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.name# author Class Author (models. Model):    name = models. Charfield (max_length=50)    email = models. Emailfield ()    def __unicode__ (self):        return self.name# Directory Class 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 Creating objects

Using Python objects to describe data in a database table, Django uses an intuitive system, a model class that describes a data table, and a detailed record of a class's instance description table. Use the model's save () method to create the object to the database.

From mysite.blog.models Import BLOGB = Blogs (name= ' Beatles blog ', tagline= ' all the latest Beatles news. ') B.save ()

Django executes SQL to write objects to the database only when the Save method is executed.


1.1.3 To save modified objects

Save changes still use the Save () method

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


1.1.4 Saving ForeignKey and Manytomanyfield fields

Cheese_blog = Blog.objects.get (name= "Cheddar talk") Entry.blog = Cheese_blog #为 manytomanyfield add record Entry.save ()
Joe = Author.objects.create (name= "Joe") Entry.authors.add (Joe) #为 ForeignKey add record


1.1.5 Retrieving objects
Retrieve objects from the database, you can build queryset through the manage of the model, a queryset is represented as a combination of objects in a database, he can have 0 one or more filter conditions, In SQL, Queryset is equivalent to a SELECT statement filtered by where or limit. You get queryset through the manage of the model, and each model has at least one manage


1.1.6 Retrieving all the objects

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

All_entries = Entry.objects.all ()


1.1.7 filtering to retrieve specific objects

There are two ways to retrieve the filtered results of a particular query.
Filter (**kwargs) returns a new match query parameter after the Queryset
Exclude (**kwargs) returns a new unmatched query parameter after the Queryset

Entry.objects.filter (pub_date__year=2006)


1.1.8 Link filtering

Entry.objects.filter (headline__startswith= ' what ')         . Exclude (Pub_date__gte=datetime.now ())         . Filter (pub_ Date__gte=datetime (2005, 1, 1))


1.1.9 Filter result set is the only

Each time you complete a queryset, you get a whole new set of results, not including 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 ())

Three querysets are separate, the first is headline with "What" the beginning of the result set, the second is a subset of the first, that is, pub_date is not much more than the present, the third is the first subset, Pub_date greater than the present


1.2.1 Result set is deferred

Querysets is deferred, creating querysets does not touch the database operation, you can merge multiple filters together, and Django will not start querying until the value is evaluated. Such as:

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 appears that three filters have been executed, Django has actually started querying the Execute SQL to the database when the print Q was finally executed.


1.2.2 Other methods of Queryset
In most cases you use all (), filter (), and Exclude ()


1.2.3 Limit Querysets

Use Python's array restriction syntax to qualify Queryset, such as:
Take the top 5

Entry.objects.all () [: 5]

Take a fifth to tenth.

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

In general, restricting Queryset returns a new Queryset and does not immediately evaluate the query 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 ()]


1.2.4 Field Lookup

A field lookup is a WHERE conditional clause that specifies the SQL statement, specifying the query keyword by means of the Queryset method filter (), exclude (), and get ().
Basic Query Field__lookuptype=value
For example:

Entry.objects.filter (pub_date__lte= ' 2006-01-01 ')

Convert to SQL:

SELECT * from Blog_entry WHERE pub_date <= ' 2006-01-01 ';

If you pass an invalid argument, it throws an exception.

The database API supports a number of query types and experiences below:
A, exact

Entry.objects.get (headline__exact= "Man Bites Dog")

Equivalent to

SELECT ... WHERE headline = ' Man Bites dog ';

If the query does not provide a double underline, then the default __exact=

Blog.objects.get (id__exact=14) # Explicit FormBlog.objects.get (id=14) # __exact is implied

b, iexact--ignore case

Blog.objects.get (name__iexact= "Beatles Blog")

Blog title will match "Beatles blog", "Beatles blog", and even "Beatles blog".

C, contains--contains query, case-sensitive

Entry.objects.get (headline__contains= ' Lennon ')

Convert to SQL

SELECT ... WHERE headline like '%lennon% ';

Icontains Case insensitive

Startswith,endswith,istartswith,iendswith
Front fuzzy matching, after fuzzy matching


1.2.5 Cross-Relationship query

Entry.objects.filter (blog__name__exact= ' Beatles blog ')

This can span the depth you want.

Reverse Cross-relationship query

Blog.objects.filter (entry__headline__contains= ' Lennon ')


If the intermediate model does not have a value across a multi-tier relational query, Django will treat it 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 filters refer to model fields

For the current example, we have created a filter that compares the value of the model field with a fixed value, but if we want to compare the values of one finger and another in the same model, Django provides F ()--an operation that specifically takes a column value from the object

From Django.db.models import FEntry.objects.filter (n_pingbacks__lt=f (' n_comments '))

Note: n_pingbacks, n_comments are model entry properties

Django supports subtraction and modulo calculations

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 Shortcut

Blog.objects.get (id__exact=14) # Explicit FormBlog.objects.get (id=14) # __exact is ImpliedBlog.objects.get (pk=14) # PK Implies Id__exact

Not limited to __exact queries

# Get blogs entries with ID 1, 4 and 7blog.objects.filter (pk__in=[1,4,7]) # Get all blogs entries with ID > 14blog.object S.filter (PK__GT=14)

Cross-query

Entry.objects.filter (blog__id__exact=3) # Explicit FormEntry.objects.filter (blog__id=3) # __exact is ImpliedEntry.objects.filter (blog__pk=3) # __PK implies __id__exact

Like statement escape percent sign

Entry.objects.filter (headline__contains= '% ')

Escaped as

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


1.2.7 Cache Query Set

Each queryset contains a cache to minimize access to the database. It's important to understand how he works, and to write the most efficient code.
In the newly created Queryset, the cache is empty. The first time the queryset is evaluated, so the database query occurs, Django puts the query results into the cache and returns to the request, and the subsequent query values are reused for the results in the cache.

Keep the cache thinking habit, because if you don't use query caching correctly, there's a problem. For example, the following example creates a two Queryset

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 executes two times, and the actual database load is two times

To avoid this problem, simply save the Queryset reuse

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


1.2.8 Comparing objects

Compare two model instances, using the Python standard operator, two equals = =

Some_entry = = Other_entrysome_entry.id = = Other_entry.idsome_obj = = Other_objsome_obj.name = Other_obj.name


1.2.9 deleting objects

Delete method is very convenient, the method named Delete (), this method directly delete the object has no return value

E.delete ()

You can also delete objects in bulk, each queryset has a delete () method to delete all objects in Queryset


1.3. Modify multiple Objects 11 times

Sometimes you want to assign a specific value to a field for 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-associative fields and foreign keys

b = Blog.objects.get (pk=1) # change every Entry so the it belongs to this Blog.Entry.objects.all (). Update (BLOG=B)

The update () method does not return any values, Queryset does not support the Save method, and if you want to execute save, you can do the following:

For item in My_queryset:item.save ()

Update can also use the F ()

# This would RAISE A FieldErrorEntry.objects.update (headline=f (' Blog__name '))

1.3.2 Relationship Object

When you define a relationship in model, the model instance has a handy API to access the relational object. Use the model above on this page for an example, a entry
Object can get the blog object, access the blog property E.blog.
Django also creates an API to access the other side of the relational object, and a blog object accesses the entry list B.entry_set.all ().


1.3.3 One-to-many Relationship

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

E = Entry.objects.get (id=2) E.blog # Returns the related blog object.

You can obtain and assign values by virtue of the foreign key property, and modify the foreign key value to know that the Execute save () method is not saved to the database

E = Entry.objects.get (id=2) E.blog = Some_bloge.save ()

If ForeignKey is set to Null=true you can assign a value of None

E = Entry.objects.get (id=2) Print E.blog # Hits The database to retrieve the associated Blog.print E.blog # will not be in the data collection; Use the values in the cache. E = Entry.objects.select_related (). Get (id=2) Print E.blog # is not being taken to the database; Use the values in the cache. Print E.blog # is not being taken to the database; Use the values in the cache. B = Blog.objects.get (id=1) B.entry_set.all () # Returns the associated object for all blogs. # B.entry_set is a Manager that returns QUERYSETS.B.E Ntry_set.filter (headline__contains= ' Lennon ') b.entry_set.count () b = Blog.objects.get (id=1) B.entries.all () # Returns the associated object 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 Relationship objects
Create (**kwargs) Create new Object
Remove (obj1, obj2, ...) Remove multiple relationship objects
Clear () Cleans up all relationship objects

b = Blog.objects.get (id=1) B.entry_set = [E1, E2]


1.3.4 Many-to-many Relationship

E = Entry.objects.get (id=3) E.authors.all () # returns Entry all authors. E.authors.count () e.authors.filter (name__contains= ' John ') A = Author.objects.get (id=5) A.entry_set.all () # returns Author all entry.


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 # Returns the entry object.

Django ORM Summary [reprint]

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.