Python-django-orm, Common Query method

Source: Internet
Author: User

Introduce some common query methods of Django model

The first is some documented help

__exactexactly equals like ' AAA '__iexactexact equals ignore case ilike ' AAA '__containsContains like '%aaa%'__icontainsContains ignore case ilike '%aaa%', but for SQLite, the effect of contains is equivalent to Icontains. __GTGreater than__gtegreater than or equal__ltless than__lteless than or equal__inexists within a list range__startswithto have a. Start__istartswithto have a. Start ignoring case__endswithto have a. End__iendswithto have a. End, ignoring case__rangein the ... Within range__yearyear of the date field__monthmonth of the date field__dayDay of the date field__isnull=true/False__isnull=true and__exactThe difference between =none

Then there are some examples of columns:

1 classBlog (models. Model):2Name = models. Charfield (max_length=100)3Tagline =models. TextField ()4 5     def __unicode__(self):6         returnSelf.name7 8 classAuthor (models. Model):9Name = models. Charfield (max_length=50)Tenemail =models. Emailfield () One      A     def __unicode__(self): -         returnSelf.name -  the classEntry (models. Model): -Blog =models. ForeignKey (Blog) -Headline = models. Charfield (max_length=255) -Body_text =models. TextField () +Pub_date =models. Datetimefield () -Authors =models. Manytomanyfield (Author) +  A     def __unicode__(self): at         returnSelf.headline

Here a entry associated with a blog and multiple authors

Some actions on an object:

  

Increase:

Through the Save () method

 from Import  = blog (name= ' Beatles blog ', tagline=' All the latest Beatles news. ') B.save ()

Modify:

You can also use the Save method

1  B5.name = ' New name '2  b5.save ()

In the context of a foreign key, you can either go directly through the parameter list or assign a value to save.

1 cheese_blog = Blog.objects.get (name="Cheddar talk")2 entry.blog = Cheese_blog 3 Entry.save ()

For many-to-many relationships, you cannot update directly, and you need a model instance. The member name of the many-to-many relationship. Add (model).

Joe = Author.objects.create (name="Joe") Entry.authors.add (Joe)

Find:

Retrieve all objects:

  

All_entries = Entry.objects.all ()

  

Retrieving a specific object
Use the following two methods:
Fileter (**kwargs)
Returns a queryset that matches the argument, equal to (=).
Exclude (**kwargs)
Returns a queryset that does not match the parameter, equal to (! =).

Queryset method

    

1 # This is the data found in the first 5 entry tables. 2 Entry.objects.all () [: 5]  3#  This is looking for data from 5th to 10th.  4 Entry.objects.all () [5:10]  5#  This is the data that queries from No. 0 to 10th, with a step of 2.  6 Entry.objects.all () [: 10:2]  7#  fuzzy query 8 Entry.objects.get (headline__contains= ' Lennon ')  

Next comes some of the cool ways that ORM offers:

  

1Entry.objects.filter (blog__name__exact=' Beatles Blog ')2 #find the Entry object of the Entry table foreign key relationship blog_name= ' Beatles Blog '. 3Blog.objects.filter (entry__headline__contains=' Lennon ')4 #Find Blog Table foreign key relationships the headline field in the Entry table contains Lennon blog data. 5Blog.objects.filter (entry__author__name=' Lennon ')6 #Find Blog Table foreign key relationships the author field in the Entry table contains Lennon blog data. 7Blog.objects.filter (entry__author__name__isnull=True)8Blog.objects.filter (entry__author__isnull=false,entry__author__name__isnull=True)9 #query for a value that is author_name nullTen  OneBlog.objects.filter (entry__headline__contains= ' Lennon ', entry__pub_date__year=2008) ABlog.objects.filter (entry__headline__contains= ' Lennon '). Filter (entry__pub_date__year=2008) - #Both of these queries are the same in some cases, and in some cases they are different. The first is to limit all the blog data, whereas the second case is the first filter - #restrict the blog, while the second filter is limited to entry the  -Blog.objects.filter (pk__in=[1,4,7]) -  #ID in 1,4,7 -Blog.objects.filter (pk__gt=14) +  #id =

Complex query for Q objects

1 Q (question__startswith= ' Who ') | Q (question__startswith=' what ')23 Poll.objects.get (q (question__startswith=  4         Q (Pub_date=date (2005, 5, 2)) | Q (Pub_date=date (2005, 5, 65         )

Delete:

Entry.objects.filter (pub_date__year=2005). Delete () Entry.objects.all (). Delete ()

Reverse query:

First show a model

  

1  fromDjango.dbImportModels2 3 classPublisher (models. Model):4 5Name = models. Charfield (max_length=30)6Address = models. Charfield (max_length=50)7City = models. Charfield (max_length=60)8State_province = models. Charfield (max_length=30)9Country = models. Charfield (max_length=50)TenWebsite =models. Urlfield () One      A     def __unicode__(self): -         returnSelf.name -      the classAuthor (models. Model): -  -First_Name = models. Charfield (max_length=30) -Last_Name = models. Charfield (max_length=40) +email =models. Emailfield () -      +     def __unicode__(self): A         returnU'%s%s'%(Self.first_name, Self.last_name) at classBook (models. Model): -  -title = models. Charfield (max_length=100) -Authors =models. Manytomanyfield (Author) -Publisher =models. ForeignKey (Publisher) -Publication_date =models. Datefield () in      -     def __unicode__(self): to     returnSelf.title

An author a book and a publishing house, a book can be written by multiple authors, but only belong to a publishing house

Reverse Query method:

  

p = Publisher.objects.get (name='Apress publishing') p.book_set.filter (name__ Icontains='Django')#  property name Book_set is made up of lowercase (such as book) plus _set of the model name.  #  through the publishing house, get a book named Django that has a foreign key associated with it

Access many-to-many:

1 B = Book.objects.get (id=50)
2 B.authors.all ()

  

    

Python-django-orm, Common Query method

Related Article

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.