Data filtering capabilities in Python's Django framework

Source: Internet
Author: User
We rarely take all of the data out of the database at once, and usually only work on a subset of the data. In the Django API, we can filter the data using the "filter ()" Method:

>>> Publisher.objects.filter (name= ' Apress ') [
 
  
   
  ]
 
  

Filter () is converted to a WHERE SQL statement according to the keyword parameter. The preceding example is equivalent to this:

SELECT ID, name, address, city, State_province, country, websitefrom books_publisherwhere name = ' Apress ';

You can pass multiple parameters to filter () to narrow the selection:

>>> Publisher.objects.filter (country= "U.S.A.", state_province= "CA") [
 
  
   
  ]
 
  

Multiple parameters are converted to and SQL clauses, so the above code can be translated into this:

SELECT ID, name, address, city, State_province, country, websitefrom books_publisherwhere country = ' U.S.A. ' and State_prov ince = ' CA ';

Note that the SQL default = operator is exactly matched, and other types of lookups can also be used:

>>> Publisher.objects.filter (name__contains= "Press") [
 
  
   
  ]
 
  

There is a double underline between name and contains. Like Python, Django uses a double underline to indicate that it will perform some magical operations. Here, the contains part will be translated into a like statement by Django:

SELECT ID, name, address, city, State_province, country, websitefrom books_publisherwhere name like '%press% ';

Some of the other lookup types are: icontains (case-insensitive like), StartsWith and EndsWith, and range (Sqlbetween query).

  • 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.