Multiple Filter-By

Example Overview

This example filters options against multiple form fields at once by passing a list of tuples to filter_by, narrowing the available articles to those matching both the selected Magazine AND the selected Status. Each condition is combined with AND logic and skipped when its field is empty, making this the pattern to use for multi-dimensional filtering such as articles by publication and status or products by category and availability.

Key Code Segments

Forms

This example uses the new list format for filter_by to specify multiple filter conditions:

Explanation:

  • The filter_by parameter accepts a list of 2-tuples: [("form_field", "lookup_field"), ...]

  • Each tuple specifies: the form field name to get the value from, and the model field to filter by

  • All conditions are combined with AND logic

  • If a form field has no value, that filter condition is skipped

How It Works

When both Magazine and Status are selected:

  1. The JavaScript reads values from both form fields

  2. The autocomplete URL includes multiple f parameters:

    ?q=search&f='magazine__magazine_id=5'&f='status__status=published'
    
  3. The server applies both filters with AND logic

  4. Only articles matching BOTH conditions are returned

Templates

This template snippet is abridged. The live template also defines a {% block extra_header %} containing {{ form.media }} and a <style> block; without {{ form.media }} the widgets render unstyled.

Implementation Notes

  • Key Features:

    • Combines multiple filter_by conditions with AND logic

    • Each filter is optional - if not selected, that condition is ignored

    • Fully backwards compatible with the single-tuple format

  • Comparison with Single Filter:

    Single Filter

    Multiple Filters

    filter_by=('field', 'lookup')

    filter_by=[('field1', 'lookup1'), ('field2', 'lookup2')]

    One condition

    Multiple AND conditions

    Form field value only

    Form field values only

See the Constant Filter-By example for filtering with constant values.