Django orm summary, djangoorm

Source: Internet
Author: User

Django orm summary, djangoorm

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:

# Blog 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 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 Blogb = 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 record entry. save () for ManyToManyField ()
Joe = Author. objects. create (name = "Joe") entry. authors. add (joe) # add a record 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='What')         .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()


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='2006-01-01')

Convert to SQL:

SELECT * FROM blog_entry WHERE pub_date <= '2006-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 formBlog.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 FEntry.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 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 blog entries with id > 14Blog.objects.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 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_entrysome_entry.id == other_entry.idsome_obj == other_objsome_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 FieldErrorEntry.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_bloge.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 # Won't be retrieved from the database; Use the cached value. e = Entry. objects. select_related (). get (id = 2) print e. blog # Won't be retrieved from the database; Use the cached value. print e. blog # Won't be retrieved from the database; Use the cached value. B = Blog. objects. get (id = 1) B. entry_set.all () # returns 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,...) to 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). entry_set.all () # returns 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.

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.