Last night, we completed a simple example to manipulate a database table. Today, we need to familiarize ourselves with more APIs for more complex functions. This step is complete, and we don't have much of a problem with small data operations.
Now, let's take a look at the Django official documentation to learn
1. Construct the data table
Copy the following to your friend charm, then execute the Migrate command
Class Blog (models. Model):
Name = models. Charfield (max_length=100)
Tagline = models. TextField ()
def __str__ (self): # __unicode__ on Python 2
Return Self.name
Class Author (models. Model):
Name = models. Charfield (max_length=200)
email = models. Emailfield ()
def __str__ (self): # __unicode__ on Python 2
Return Self.name
Class Entry (models. Model):
Blog = models. ForeignKey (Blog)
Headline = models. Charfield (max_length=255)
Body_text = models. TextField ()
Pub_date = models. Datefield ()
Mod_date = models. Datefield ()
Authors = models. Manytomanyfield (Author)
N_comments = models. Integerfield ()
N_pingbacks = models. Integerfield ()
Rating = models. Integerfield ()
def __str__ (self): # __unicode__ on Python 2
Return Self.headline
2. Create an Object
b = Blog (name= ' Beatles blog ', tagline= ' all the latest Beatles news. ')
B.save ()
So we're going to put the data in.
The same object, which is saved and then re-assigned, will perform the modify operation
3. Save ForeignKey and Manytomanyfield fields
Now that our data has been saved, and we have established an association
In model, entry is associated with a foreign key blog (ForeignKey)
So when you create a entry, you need to get a blog object, assign a value to entry, and then perform the operation of saving the database.
Entry = entry (headline= ' test123 ', body_text= ' test123 ', Pub_date=datetime.datetime.now (),
Mod_date=datetime.datetime.now (), n_comments=123, n_pingbacks=456, rating=789)
Cheese_blog = Blog.objects.get (name= "Beatles blog")
Entry.blog = Cheese_blog
Entry.save ()
Now, dealing with the manytomanyfield situation.
It has to be taken out:
data = Entry.authors.iterator ()
Direct access to attributes and turn the query set into an iterative
4. Querying objects
All_entries = Entry.objects.all ()
5. Search by condition
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)
Q2 = Q1.exclude (Pub_date__gte=datetime.date.today ())
6. Link Query
Entry.objects.filter (headline__startswith= ' what ')
. Exclude (Pub_date__gte=datetime.now ())
. Filter (Pub_date__gte=datetime (2005, 1, 1))
7. Deferred Query
Creating querysets does not touch the database operation, you can merge multiple filters together until Django starts querying when the value is evaluated
Q = Entry.objects.filter (headline__startswith= "what")
Q = Q.filter (Pub_date__lte=datetime.now ())
Q = q.exclude (body_text__icontains= "food")
8. Retrieving a single object
One_entry = Entry.objects.get (pk=1)
9. Restricted query: Paging/sorting query
Entry.objects.all () [: 5]
Entry.objects.order_by (' headline ') [0:1].get ()
10. Field Query
Entry.objects.filter (pub_date__lte= ' 2006-01-01 ')
Convert to SQL:
SELECT * from Blog_entry WHERE pub_date <= ' 2006-01-01 ';
11.exact
Entry.objects.get (headline__exact= "Man Bites Dog")
Convert to SQL:
SELECT ... WHERE headline = ' Man Bites dog ';
12.iexact--ignoring case
Blog.objects.get (name__iexact= "Beatles Blog")
13.contains--contains queries, case sensitive
Entry.objects.get (headline__contains= ' Lennon ')
Convert to SQL:
SELECT ... WHERE headline like '%lennon% ';
Icontains Case insensitive
Startswith,endswith,istartswith,iendswith
Fuzzy query before and after
14. Connection Query
Query Blog__name match, return entry
Entry.objects.filter (blog__name__exact= ' Beatles blog ')
Query Entry__headline match, return blog
Blog.objects.filter (entry__headline__contains= ' Lennon ')
If the intermediate model does not have a value across a multi-tier relational query, Django treats 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);
A 15.F object that operates on a field. Just like in SQL, column a +b column. F objects are seldom used
From Django.db.models import F
Entry.objects.filter (n_pingbacks__lt=f (' n_comments '))
Column subtraction All can
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 '))
16.like statement Escape percent sign
Entry.objects.filter (headline__contains= '% ')
Escaped as:
SELECT ... WHERE headline like '%\%% ';
17. Delete
Q = Entry.objects.filter (headline__startswith= "what")
Q.delete ()
18. Batch Modification
Entry.objects.filter (pub_date__year=2007). Update (headline= ' Everything is the same ')
One-time modification of all entry blog Properties point to
b = Blog.objects.get (pk=1)
Entry.objects.all (). Update (BLOG=B)
Update can also use the F ()
Entry.objects.update (headline=f (' Blog__name '))
19.one-to-many relationship
E = Entry.objects.get (id=2)
Print E.blog # Hits The database to retrieve the associated blog
E = Entry.objects.select_related (). Get (id=2)
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.entry_set.filter (headline__contains= ' Lennon ')
B.entry_set.count ()
b = Blog.objects.get (id=1)
B.entries.all () # Returns the associated object for all blogs
# b.entries is a Manager that returns querysets.
B.entries.filter (headline__contains= ' Lennon ')
B.entries.count ()
Add (Obj1, Obj2, ...) make connections to multiple objects
Create (**kwargs) Create new Object
Remove (obj1, obj2, ...) Remove multiple relationship objects
Clear () Cleans up all relationship objects
20.many-to-many relationship
E = Entry.objects.get (id=3)
E.authors.all () # Return entry all authors
E.authors.count ()
E.authors.filter (name__contains= ' John ')
A = Author.objects.get (id=5)
A.entry_set.all () # Return author all entry
21.one-to-one relationship
To set when defining a model
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 Operations Database Common API