Bird
Raised Fist0
Djangoframework~20 mins

Filtering with django-filter - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
django-filter Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output of this django-filter setup?

Given a Django model Book with fields title (string) and year (integer), and this filter class:

import django_filters

class BookFilter(django_filters.FilterSet):
    class Meta:
        model = Book
        fields = {"year": ["gte", "lte"]}

What will BookFilter({'year__gte': 2000}).qs return?

Django
import django_filters

class BookFilter(django_filters.FilterSet):
    class Meta:
        model = Book
        fields = {"year": ["gte", "lte"]}

# Assume Book.objects.all() contains books with years 1995, 2000, 2005
AA queryset of books with year >= 2000
BA queryset of books with year <= 2000
CRaises a TypeError due to incorrect filter syntax
DA queryset of all books ignoring the filter
Attempts:
2 left
💡 Hint

Look at the filter field name and the query parameter key.

📝 Syntax
intermediate
2:00remaining
Which option correctly defines a filter for a CharField with case-insensitive contains?

Choose the correct django-filter field definition to filter a name CharField with case-insensitive substring matching.

Django
import django_filters

class PersonFilter(django_filters.FilterSet):
    name = ???

    class Meta:
        model = Person
        fields = ['name']
Aname = django_filters.CharFilter(lookup_expr='contains')
Bname = django_filters.CharFilter(lookup_expr='icontains')
Cname = django_filters.CharFilter(lookup_expr='iexact')
Dname = django_filters.CharFilter(lookup_expr='startswith')
Attempts:
2 left
💡 Hint

Look for the lookup expression that ignores case and checks substring.

🔧 Debug
advanced
2:00remaining
Why does this filter raise a FieldError?

Given this filter class:

class ProductFilter(django_filters.FilterSet):
    price = django_filters.NumberFilter(lookup_expr='gte')

    class Meta:
        model = Product
        fields = ['price', 'category']

And the query ProductFilter({'price__gte': 100}).qs raises django.core.exceptions.FieldError. Why?

Django
class ProductFilter(django_filters.FilterSet):
    price = django_filters.NumberFilter(lookup_expr='gte')

    class Meta:
        model = Product
        fields = ['price', 'category']

# Product model has fields: price (DecimalField), category (ForeignKey)
ABecause 'category' field is missing a filter definition
BBecause 'price__gte' is not a valid query parameter for NumberFilter with lookup_expr='gte'
CBecause the Product model does not have a 'price' field
DBecause the filter field 'price' already uses 'gte', the query param should be 'price' not 'price__gte'
Attempts:
2 left
💡 Hint

Check how django-filter builds query parameters from filter fields and lookup expressions.

state_output
advanced
2:00remaining
What is the count of items in the filtered queryset?

Given a model Order with a status CharField and this filter:

class OrderFilter(django_filters.FilterSet):
    status = django_filters.CharFilter(lookup_expr='exact')

    class Meta:
        model = Order
        fields = ['status']

# Assume Order.objects.all() has 10 orders: 4 with status 'pending', 6 with status 'shipped'

What is OrderFilter({'status': 'pending'}).qs.count()?

Django
class OrderFilter(django_filters.FilterSet):
    status = django_filters.CharFilter(lookup_expr='exact')

    class Meta:
        model = Order
        fields = ['status']

# Orders: 4 pending, 6 shipped
A4
B6
C10
D0
Attempts:
2 left
💡 Hint

Filter matches exact status 'pending'.

🧠 Conceptual
expert
3:00remaining
Which option best explains how django-filter applies filters internally?

How does django-filter apply filters to a queryset when you call FilterSet(data).qs?

AIt modifies the original queryset in place by removing items that don't match the filter criteria.
BIt converts the filter data into raw SQL and executes it directly on the database.
CIt builds a Django ORM query by chaining <code>filter()</code> calls using the filter fields and their lookup expressions with the provided data.
DIt loads all objects into memory and filters them using Python list comprehensions.
Attempts:
2 left
💡 Hint

Think about how Django ORM queries are built and executed lazily.

Practice

(1/5)
1. What is the main purpose of using django-filter in a Django project?
easy
A. To create database tables automatically
B. To easily filter querysets based on user input without writing complex code
C. To handle user authentication and permissions
D. To generate HTML forms for user registration

Solution

  1. Step 1: Understand django-filter's role

    django-filter is designed to simplify filtering data in Django apps by creating filters for querysets.
  2. Step 2: Compare with other options

    Options A, C, and D relate to database creation, authentication, and form generation, which are not the main purpose of django-filter.
  3. Final Answer:

    To easily filter querysets based on user input without writing complex code -> Option B
  4. Quick Check:

    django-filter purpose = filtering querysets [OK]
Hint: django-filter = easy queryset filtering [OK]
Common Mistakes:
  • Confusing django-filter with authentication libraries
  • Thinking it creates database tables
  • Assuming it generates forms for registration
2. Which of the following is the correct way to define a FilterSet class for a model named Book with a filter on the author field?
easy
A. class BookFilter(FilterSet):\n class Meta:\n model = Book\n fields = ['author']
B. class BookFilter(FilterSet):\n model = Book\n fields = ['author']
C. class BookFilter(FilterSet):\n class Meta:\n fields = ['author']
D. class BookFilter(FilterSet):\n class Meta:\n model = Book\n filter_fields = ['author']

Solution

  1. Step 1: Recall FilterSet Meta class structure

    The Meta class must specify the model and the fields list for filtering.
  2. Step 2: Check each option

    class BookFilter(FilterSet):\n class Meta:\n model = Book\n fields = ['author'] correctly defines Meta with model and fields. class BookFilter(FilterSet):\n model = Book\n fields = ['author'] misses Meta class. class BookFilter(FilterSet):\n class Meta:\n fields = ['author'] misses model. class BookFilter(FilterSet):\n class Meta:\n model = Book\n filter_fields = ['author'] uses incorrect attribute 'filter_fields'.
  3. Final Answer:

    class BookFilter(FilterSet):\n class Meta:\n model = Book\n fields = ['author'] -> Option A
  4. Quick Check:

    FilterSet Meta needs model and fields [OK]
Hint: FilterSet Meta needs model and fields list [OK]
Common Mistakes:
  • Omitting the Meta class
  • Using 'filter_fields' instead of 'fields'
  • Not specifying the model in Meta
3. Given the following FilterSet and queryset, what will be the result of filtering with author='Alice'?
class BookFilter(FilterSet):
    class Meta:
        model = Book
        fields = ['author']

books = Book.objects.all()
filtered_books = BookFilter({'author': 'Alice'}, queryset=books).qs
medium
A. A queryset containing only books where the author field is 'Alice'
B. A queryset containing all books regardless of author
C. An empty queryset because 'author' is not a valid filter
D. A syntax error due to incorrect FilterSet usage

Solution

  1. Step 1: Understand FilterSet filtering

    Providing {'author': 'Alice'} filters the queryset to only include books with author 'Alice'.
  2. Step 2: Confirm no errors in code

    The FilterSet is correctly defined and used, so no syntax or runtime errors occur.
  3. Final Answer:

    A queryset containing only books where the author field is 'Alice' -> Option A
  4. Quick Check:

    FilterSet filters queryset by given field values [OK]
Hint: FilterSet with dict filters queryset by those values [OK]
Common Mistakes:
  • Assuming it returns all books without filtering
  • Thinking 'author' is invalid filter
  • Confusing FilterSet with form validation errors
4. Identify the error in this FilterSet usage:
class BookFilter(FilterSet):
    class Meta:
        model = Book
        fields = ['title']

filter = BookFilter(request.GET)
filtered_books = filter.qs
medium
A. FilterSet class must inherit from django.forms.Form
B. Incorrect attribute name; should be filter.queryset instead of filter.qs
C. Fields list should include 'author' not 'title'
D. Missing queryset argument when creating BookFilter instance

Solution

  1. Step 1: Check FilterSet instantiation

    BookFilter requires a queryset argument to filter; it's missing here.
  2. Step 2: Verify attribute usage

    Using filter.qs is correct to get filtered queryset; no error there.
  3. Final Answer:

    Missing queryset argument when creating BookFilter instance -> Option D
  4. Quick Check:

    FilterSet needs queryset argument [OK]
Hint: Always pass queryset when instantiating FilterSet [OK]
Common Mistakes:
  • Forgetting to pass queryset argument
  • Using wrong attribute like filter.queryset
  • Confusing FilterSet with Django forms inheritance
5. You want to filter a list of Product objects by price range using django-filter. Which FilterSet definition correctly allows filtering products with price greater than or equal to a minimum and less than or equal to a maximum?
hard
A. class ProductFilter(FilterSet): price = RangeFilter() class Meta: model = Product fields = ['price']
B. class ProductFilter(FilterSet): class Meta: model = Product fields = ['price__gte', 'price__lte']
C. class ProductFilter(FilterSet): price_min = NumberFilter(lookup_expr='gte') price_max = NumberFilter(lookup_expr='lte') class Meta: model = Product fields = ['price_min', 'price_max']
D. class ProductFilter(FilterSet): price_min = RangeFilter(field_name='price', lookup_expr='gte') price_max = RangeFilter(field_name='price', lookup_expr='lte') class Meta: model = Product fields = ['price_min', 'price_max']

Solution

  1. Step 1: Understand django-filter range filters

    RangeFilter allows filtering between min and max values on a single field.
  2. Step 2: Evaluate options

    class ProductFilter(FilterSet): price = RangeFilter() class Meta: model = Product fields = ['price'] uses RangeFilter but it filters a range with a single field; however, RangeFilter does not split into min and max filters automatically. class ProductFilter(FilterSet): class Meta: model = Product fields = ['price__gte', 'price__lte'] uses invalid field names with double underscores in fields list, which is incorrect. class ProductFilter(FilterSet): price_min = NumberFilter(lookup_expr='gte') price_max = NumberFilter(lookup_expr='lte') class Meta: model = Product fields = ['price_min', 'price_max'] defines two NumberFilters with lookup expressions 'gte' and 'lte' on the same field 'price' and includes them correctly in fields list; this is the correct approach. class ProductFilter(FilterSet): price_min = RangeFilter(field_name='price', lookup_expr='gte') price_max = RangeFilter(field_name='price', lookup_expr='lte') class Meta: model = Product fields = ['price_min', 'price_max'] incorrectly uses RangeFilter twice with lookup_expr, which is not supported.
  3. Final Answer:

    class ProductFilter(FilterSet): price_min = NumberFilter(lookup_expr='gte') price_max = NumberFilter(lookup_expr='lte') class Meta: model = Product fields = ['price_min', 'price_max'] -> Option C
  4. Quick Check:

    Use NumberFilter with lookup_expr for min and max filtering [OK]
Hint: Use NumberFilter with lookup_expr for min and max [OK]
Common Mistakes:
  • Using NumberFilter but listing wrong fields
  • Trying to use RangeFilter with lookup_expr
  • Specifying field names with double underscores in fields list