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