Filters
Using a model's filter()
function you can query to the database with certain conditions. For example, to retrieve all courses with more than ten enrolled students you can write:
>>> courses = Course.objects.filter(enrolled_students__gt=10)
The syntax is as follows: the names of the fields by which you want to filter are passed as arguments (in this case, only enrolled_students
) followed by a double underscore and some specific filter (gt
, which means "greater than".) Conversely, to retrieve courses with less than ten students use:
>>> courses = Course.objects.filter(enrolled_students__lt=10)
The gte
and lte
filters are also available, that is, "greater than or equal" and "less than or equal."
If you want to get courses that have exactly ten students, just write:
>>> courses = Course.objects.filter(enrolled_students=10)
The greater/less than filters work, of course, with numeric fields. For text fields like CharField
Django provides the following filters:
contains
/icontains
startswith
/istartswith
endswith
/iendswith
contains
is equivalent to Python's in
operator. For example, this code fetches all courses whose names contain an "x":
>>> courses = Course.objects.filter(name__contains="x")
startswith
and endswith
are equivalent to the Python string methods of the same name. For example, this is how you get courses that begin with "P":
>>> courses = Course.objects.filter(name__startswith="P")
Variants of these filters that begin with an "i" perform the comparison in a case-insensitive manner.
Finally, you can combine several filters:
>>> courses = Course.objects.filter(name__startswith="P", enrolled_students__gt=10)
This fetches courses starting with "P" and having 10 enrolled students.