Django provides a powerful and flexible way to filter data. Filters can be used to easily manipulate and transform data based on specific criteria. Below is a brief overview of the Django Filters documentation.
Overview of Filters
Django Filters allow you to perform operations on your data. You can use them to filter data in your models, or even on data that is already loaded into your templates.
Basic Usage
To use a filter, you simply pass the name of the filter as a string to the filter()
method. For example:
filtered_data = my_query.filter(name__icontains="John")
This will return all objects in my_query
where the name
field contains "John".
Common Filters
Django comes with a variety of built-in filters that you can use. Here are some of the most commonly used ones:
__icontains
: Case-insensitive contains.__contains
: Contains.__startswith
: Starts with.__endswith
: Ends with.__range
: Range filter.
Example
Suppose you have a Person
model with a date_of_birth
field. You can filter people born in a specific year using the __range
filter:
people_born_in_1980 = Person.objects.filter(date_of_birth__range=("1980-01-01", "1980-12-31"))
Filters in Templates
You can also use filters in your Django templates. To do this, you use the |
operator. For example:
{% for person in people %}
{{ person.name|lower }}
{% endfor %}
This will display each person's name in lowercase.
More Information
For more detailed information on Django Filters, please refer to the Django Documentation.
Related Links
- Django Model Filters
- [Django Template Filters](/en/Python/Frameworks/Django/Documentation/ Templates/Template-Tags/Filter- Tags/)
[center]
[center]