Data Models Sample:
fromDjango.dbImportModelsclassBlog (models. Model): Name= Models. Charfield (max_length=100) Tagline=models. TextField ()def __str__(self):#__unicode__ on Python 2 returnSelf.nameclassAuthor (models. Model): Name= Models. Charfield (max_length=50) Email=models. Emailfield ()def __str__(self):#__unicode__ on Python 2 returnSelf.nameclassEntry (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 returnSelf.headline
1. Create record (object)
To represent database-table data in Python objects, Django uses an intuitive (intuitive) SYSTEM:A model class represents A Datab ASE table, and an instance of this class represents a particular record in the database table.
>>> from blog.models import blog>>> b = blog (name= ' Beatles blog ', tagline= ' all the latest Beatles news. ') ) >>> B.save ()
This performs an INSERT
SQL statement behind the scenes. Django doesn ' t hits the database until you explicitly call save()
.
The save()
method has no return value.
2.1 Save record changes to database
>>> B5 = Blog.objects.get (pk=1) >>> b5.name = ' New name ' >>> b5.save ()
2.2 Saving changes to foreign key fields and many-to-many fields
>>> from blog.models import entry>>> Entry = Entry.objects.get (pk=1) >>> Cheese_blog = Blog.objects.get (name= "Cheddar talk") >>> Entry.blog = cheese_blog>>> Entry.save ()
Add one record to Manytomanyfield
>>> from blog.models import author>>> Joe = Author.objects.create (name= "Joe") >>> Entry.authors.add (Joe)
Add multiple records to Manytomanyfield
>>> John = Author.objects.create (name= "John") >>> Paul = Author.objects.create (name= "Paul") >> > George = Author.objects.create (name= "George") >>> Ringo = Author.objects.create (name= "Ringo") >> > Entry.authors.add (John, Paul, George, Ringo)
3. Inquiry Form Record
3.1 Query table all records (objects):
>>> all_entries = Entry.objects.all () # All () a result set (list) contains records for all database tables
3.2. Filter query specific records for special tables (objects)
filter(**kwargs)
Returns a new QuerySet
containing objects that match the given lookup parameters.
exclude(**kwargs)
Returns a new QuerySet
containing objects that does not match the given lookup parameters.
Note: Filter Returns a result set (list)
1Entry.objects.filter (pub_date__year=2006) query All release dates are 2006 entry2Entry.objects.all (). Filter (pub_date__year=2006)#equivalent to the above statement3 4 Support Chain Query5 6>>>Entry.objects.filter (7... headline__startswith=' What'8 ... ). Exclude (9... pub_date__gte=Datetime.date.today ()Ten ... ). Filter ( One... Pub_date__gte=datetime (2005, 1, 30) A ... ) - - the The filter query is independent, Q2,Q3, and does not affect the results of Q1 - ->>> q1 = Entry.objects.filter (headline__startswith=" What") ->>> q2 = Q1.exclude (pub_date__gte=datetime.date.today ()) +>>> q3 = Q1.filter (Pub_date__gte=datetime.date.today ())
Querysets is lazy.
>>> q = Entry.objects.filter (headline__startswith="what")>> > q = Q.filter (pub_date__lte=datetime.date.today ())>>> q = q.exclude (body_text__icontains=" Food")print(q) The preceding three statements do not actually fetch data from the database until the fourth statement, when we go to print the results, we actually get the data from the database
3.3. Query a single record by The Get () method (objects)
When we explicitly know that only one record satisfies our query, we can use Get (),>>> one_entry = Entry.objects.get (pk=1) Note: When using GET, If only more than one record is satisfied, Django throws a multipleobjectsreturned exception, and when the filter method is used, the list of multiple records is returned, and when no record is satisfied, get () throws doesnotexist; Filter does not throw an exception, only returns an empty list
In most cases, we only need to all()
use get()
, filter()
and exclude()
These methods to query, all other methods can be viewed here, https://docs.djangoproject.com/en/1.9/ref/ models/querysets/#queryset-api
3.4 Restricted query Set
Entry.objects.all () [:5] # Returns the first 5 records of Entry, equivalent to the SELECT * from Entry limit 5;entry.objects.all () [ 5] # returns sixth to tenth record, equivalent to select * from entry limit 5 offset 5; Entry.objects.all () [-1] # does not support negative indexes Entry.objects.all () [::2 ] #指定切片的步长Entry. objects.order_by ('headline') [0] # Entry the first record after sorting by the headline field. Equivalent to select * from entry order by limit 1;
3.5 field Lookups
Field lookups is specify the meat of an SQL WHERE
clause. They ' re specified as keyword arguments QuerySet
filter()
to the methods, exclude()
and get()
.
syntax format: field__lookuptype=value (double underline)
>>> Entry.objects.filter(Pub_date__lte='2006-01-01') equivalent to: SELECT* FROM Blog_entry WHERE pub_date <='2006-01-01'; field must be modelsclass'sField name in addition to double underline this format, there is also a form, foreign key field name _id,entry.objects.filter (blog_id=4) The entry object of the blog #查询所有属于 id = 4
Exact
Entry. Objects. Get(headline__exact="Cat bites dog") #精确匹配查询; equivalent to: SELECT ... WHERE Headline = ' Cat bites dog ';
blog. Objects. Get (id=14) equivalent to blogobjects. Get (id__excat=14)
iexact:
Case insensitive characters Match
Blog. Objects. Get(name__iexact="beatles Blog")
Would match a Blog
titled "Beatles Blog"
, "beatles blog"
or even "BeAtlES blOG"
.
Contains with the same icontains:
Fuzzy matching
Entry. Objects. Get(headline__contains=' Lennon ') is equivalent to sql: SELECT ... WHERE headline like '%lennon% ';
startswith
,endswith,istartswith
, iendswith
For all field lookups, please refer to https://docs.djangoproject.com/en/1.9/ref/models/querysets/#field-lookups
3.6 Multi-Table Association queries
Entry.objects.filter (Blog__name= " beatles Blog ") # This example retrieves all Entry objects with a blog whose name is ' Beatles blog ':
equivalent to sql:
also supports reverse operation: Blog.objects.filter (entry__headline__contains = " lennon ") #This example retrieves All blog
objects which has at least one entry
whose headline
contains ' Lennon '
:
equivalent to sql:
Django ORM Operations