Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 39 ยท Filtering, Pagination and Throttling

Search and Ordering in DRF

Add free-text search and client-controlled sorting to Django REST Framework endpoints with SearchFilter and OrderingFilter, search prefixes, safe ordering fields and a custom filter backend.

Field filters answer precise questions: genre equals fantasy, price below 20. Two other needs show up in almost every API: a single search box that looks in several columns, and a way to sort the results. DRF ships a backend for each, with no extra package. Both live in rest_framework.filters.

You can stack backends: every backend in filter_backends runs in order, each narrowing or re-ordering the queryset the previous one produced. That is how one endpoint can support ?genre=tech&search=python&ordering=-price.

SearchFilter

SearchFilter reads the search query parameter and checks it against the columns in search_fields. It splits the term on whitespace and requires every word to match at least one of the fields (case-insensitive, icontains by default).

You can change the matching style with a prefix on each field name:

Prefix Lookup Meaning
none icontains substring anywhere (default)
^ istartswith starts with
= iexact exact match
@ full-text search database-specific, PostgreSQL and MySQL only
$ iregex regular expression

Quote a phrase in the query to keep its words together: ?search="dark roots". Fields on related models work with double underscores, for example author__name.

Python SearchFilter with prefixes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Output:

TEXT
'python' -> ['Python by Doing']
'lin' -> ['Night Trains', 'Salt and Iron', 'Maps of Nowhere']
'science' -> ['Atlas of Storms', 'Cells and Stars', 'Deep Roots']
'scien' -> []
'ada fiction' -> ['Night Trains', 'Maps of Nowhere']
'' -> ['Night Trains', 'Salt and Iron', 'The Quiet Harbor', 'Learning Rust Slowly', 'Gardens of Glass', 'Python by Doing', 'Small Kitchens', 'Bread at Dawn', 'Maps of Nowhere', 'Atlas of Storms', 'Cells and Stars', 'Deep Roots']

Remember the cost: icontains (and ^ on most databases when the index cannot be used) scans rows. For small tables that is fine. For large ones use PostgreSQL's full-text search (@) or an external engine such as Meilisearch or Elasticsearch, and expose it through a custom backend.

To rename the parameter, set search_param = "q" on a SearchFilter subclass, or set SEARCH_PARAM in the REST_FRAMEWORK settings.

OrderingFilter

OrderingFilter reads the ordering parameter. Values are column names, - in front means descending, and commas combine several: ?ordering=genre,-price.

Two attributes control it:

  • ordering_fields: the columns clients are allowed to sort by. If you omit it, DRF permits any field on the serializer, which can include slow or sensitive ones. Always set it.
  • ordering: the default order when the client sends no parameter.
Python OrderingFilter with a whitelist

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Output:

TEXT
{} -> ['Atlas of Storms (24.00)', 'Bread at Dawn (17.50)', 'Cells and Stars (27.50)', 'Deep Roots (19.90)'] ...
{'ordering': '-price'} -> ['Learning Rust Slowly (39.90)', 'Python by Doing (29.00)', 'Cells and Stars (27.50)', 'Atlas of Storms (24.00)'] ...
{'ordering': 'year'} -> ['Deep Roots (19.90)', 'The Quiet Harbor (9.99)', 'Maps of Nowhere (11.00)', 'Bread at Dawn (17.50)'] ...
{'ordering': '-year,title'} -> ['Learning Rust Slowly (39.90)', 'Python by Doing (29.00)', 'Atlas of Storms (24.00)', 'Salt and Iron (15.00)'] ...
{'ordering': 'author'} -> ['Atlas of Storms (24.00)', 'Bread at Dawn (17.50)', 'Cells and Stars (27.50)', 'Deep Roots (19.90)'] ...

A requested field that is not in ordering_fields is ignored rather than rejected; the default order is used. This is why a stable tie-breaker matters. If many rows share a value (for example the same year), their relative order is undefined unless you add a second column such as id. Unstable ordering is also a common source of duplicated or missing rows between pages. See Pagination.

Putting all three backends together

You can stack DjangoFilterBackend, SearchFilter and OrderingFilter on one view. A typical read-only listing endpoint then supports exact filters, free text and sorting at once, which covers 90% of what front ends need.

A custom filter backend

When your rule does not fit a field or a search term, write a backend. Subclass BaseFilterBackend and implement filter_queryset(request, queryset, view). This is also the right place for rules that read other settings of the request, for example "hide out-of-stock items unless the client asks for them" or "limit to the current tenant".

Python A custom BaseFilterBackend

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Output:

TEXT
default list: 9 books; with the flag: 12 books
backends combine: ['Atlas of Storms', 'Gardens of Glass']
with out-of-stock: ['The Quiet Harbor (sold out)', 'Gardens of Glass (in stock)', 'Atlas of Storms (in stock)']

Backends run in list order, and filter_queryset() receives the queryset left by the previous one. A backend that replaces the queryset instead of narrowing it would discard earlier work, so always start from the queryset argument.

Common mistakes

  • No ordering_fields. Clients can then sort by any serializer field, including expensive computed ones.
  • No tie-breaker. Ordering by a non-unique column makes pagination unreliable; add id as a last key.
  • Searching a huge table with icontains. Use database full-text search or a dedicated engine.
  • Treating search as security. Hiding rows from the search box is not access control; use get_queryset().

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In search_fields, what does the prefix = mean?

    = is iexact, ^ is istartswith, @ is full-text search and $ is iregex.
  2. 2. A client sends ?search=ada fiction. How does SearchFilter treat the two words?

    Words are split on whitespace and combined with AND; quote them to search for a phrase.
  3. 3. What happens when ?ordering names a field that is not in ordering_fields?

    Fields outside the whitelist are dropped silently. Always define ordering_fields.
  4. 4. What must a custom filter backend implement?

    BaseFilterBackend calls filter_queryset() and expects the (narrowed) queryset back.

Summary

  • SearchFilter reads ?search= and matches every word against search_fields; prefixes change the lookup.
  • OrderingFilter reads ?ordering= (- for descending, commas for several); always set ordering_fields and a default ordering.
  • Stack backends freely: each narrows the result of the one before.
  • Custom rules go in a BaseFilterBackend subclass.
  • For serious text search on big tables, use database full-text or an external engine.

Next: Pagination