Convert Figma logo to code with AI

carltongibson logodjango-filter

A generic system for filtering Django QuerySets based on user selections

4,415
767
4,415
78

Top Related Projects

Web APIs for Django. 🎸

79,088

The Web framework for perfectionists with deadlines.

A configurable set of panels that display various debug information about the current request/response.

Django model mixins and utilities.

This is a repository for collecting global custom management extensions for the Django Framework.

Silky smooth profiling for Django

Quick Overview

Django-filter is a reusable Django application for allowing users to filter querysets dynamically. It provides a simple way to filter down a queryset based on parameters a user provides, making it easier to create complex search and filter functionality in Django projects.

Pros

  • Easy integration with Django's class-based views and REST framework
  • Highly customizable with various filter types and options
  • Supports both function-based and class-based views
  • Extensive documentation and active community support

Cons

  • Can be overkill for simple filtering needs
  • Learning curve for advanced customizations
  • Performance may degrade with very large datasets or complex filters
  • Some edge cases may require custom implementation

Code Examples

  1. Basic filter setup:
from django_filters import FilterSet
from .models import Product

class ProductFilter(FilterSet):
    class Meta:
        model = Product
        fields = ['name', 'price', 'category']
  1. Custom filter method:
from django_filters import FilterSet, CharFilter
from .models import Book

class BookFilter(FilterSet):
    author_name = CharFilter(method='filter_by_author_name')

    class Meta:
        model = Book
        fields = ['title', 'author_name']

    def filter_by_author_name(self, queryset, name, value):
        return queryset.filter(author__name__icontains=value)
  1. Using filters in a view:
from django_filters.views import FilterView
from .models import Product
from .filters import ProductFilter

class ProductListView(FilterView):
    model = Product
    filterset_class = ProductFilter
    template_name = 'product_list.html'

Getting Started

  1. Install django-filter:

    pip install django-filter
    
  2. Add 'django_filters' to INSTALLED_APPS in settings.py:

    INSTALLED_APPS = [
        ...
        'django_filters',
    ]
    
  3. Create a filter class for your model:

    from django_filters import FilterSet
    from .models import YourModel
    
    class YourModelFilter(FilterSet):
        class Meta:
            model = YourModel
            fields = ['field1', 'field2', 'field3']
    
  4. Use the filter in your view:

    from django_filters.views import FilterView
    from .filters import YourModelFilter
    
    class YourModelListView(FilterView):
        filterset_class = YourModelFilter
        template_name = 'your_template.html'
    

Competitor Comparisons

Web APIs for Django. 🎸

Pros of Django REST Framework

  • More comprehensive API development toolkit with serializers, viewsets, and authentication
  • Extensive documentation and large community support
  • Integrates well with other Django components and third-party packages

Cons of Django REST Framework

  • Steeper learning curve due to its extensive feature set
  • Can be overkill for simple API projects
  • Performance overhead for complex serializers and nested relationships

Code Comparison

Django REST Framework:

from rest_framework import viewsets

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

Django Filter:

from django_filters import rest_framework as filters

class UserFilter(filters.FilterSet):
    class Meta:
        model = User
        fields = ['username', 'email']

Summary

Django REST Framework is a full-featured API development toolkit, while Django Filter focuses specifically on filtering querysets. DRF offers more functionality but may be complex for simple projects, whereas Django Filter is lightweight and easy to implement for its specific purpose. Both can be used together in larger projects to create powerful and flexible APIs.

79,088

The Web framework for perfectionists with deadlines.

Pros of Django

  • Comprehensive web framework with built-in features for routing, ORM, authentication, and more
  • Large, active community with extensive documentation and third-party packages
  • Batteries-included approach, providing a complete solution for web development

Cons of Django

  • Heavier and more complex than specialized libraries like django-filter
  • May include unnecessary features for projects that only need filtering functionality
  • Steeper learning curve for developers who only require filtering capabilities

Code Comparison

Django (built-in filtering):

from django.db.models import Q

queryset = MyModel.objects.filter(Q(field1__icontains='value') | Q(field2__gt=10))

django-filter:

import django_filters

class MyModelFilter(django_filters.FilterSet):
    field1 = django_filters.CharFilter(lookup_expr='icontains')
    field2 = django_filters.NumberFilter(lookup_expr='gt')

    class Meta:
        model = MyModel
        fields = ['field1', 'field2']

Summary

Django is a full-featured web framework, while django-filter is a specialized library for filtering querysets. Django offers a complete solution for web development but may be overkill for projects that only need filtering. django-filter provides a more focused and flexible approach to filtering, making it easier to implement complex filters with less code.

A configurable set of panels that display various debug information about the current request/response.

Pros of django-debug-toolbar

  • Provides a comprehensive set of debugging tools directly in the browser
  • Offers real-time performance analysis and SQL query inspection
  • Highly customizable with various panels for different debugging needs

Cons of django-debug-toolbar

  • Primarily focused on development and debugging, not for production use
  • Can impact performance when enabled, especially for complex applications
  • Requires additional configuration for use in production environments

Code Comparison

django-debug-toolbar:

INSTALLED_APPS = [
    # ...
    'debug_toolbar',
]

MIDDLEWARE = [
    # ...
    'debug_toolbar.middleware.DebugToolbarMiddleware',
]

django-filter:

INSTALLED_APPS = [
    # ...
    'django_filters',
]

# In views.py
from django_filters.views import FilterView

django-debug-toolbar is a powerful development tool for Django applications, providing in-browser debugging information. It excels at performance analysis and SQL query inspection but is primarily intended for development use. django-filter, on the other hand, focuses on filtering querysets in Django applications, making it more suitable for production use in implementing search and filtering functionality. While django-debug-toolbar offers comprehensive debugging features, django-filter provides a streamlined approach to data filtering, each serving different purposes in Django development.

Django model mixins and utilities.

Pros of django-model-utils

  • Provides a wide range of utility mixins and model fields for Django models
  • Offers TimeStampedModel for automatic creation and modification time tracking
  • Includes StatusModel for easy management of model status fields

Cons of django-model-utils

  • Less focused on filtering functionality compared to django-filter
  • May require more manual implementation for complex querying scenarios
  • Not specifically designed for API-based filtering

Code Comparison

django-model-utils:

from model_utils.models import TimeStampedModel

class MyModel(TimeStampedModel):
    name = models.CharField(max_length=100)

django-filter:

import django_filters

class ProductFilter(django_filters.FilterSet):
    name = django_filters.CharFilter(lookup_expr='icontains')
    class Meta:
        model = Product
        fields = ['name', 'price', 'category']

Summary

django-model-utils is a versatile toolkit for enhancing Django models with useful mixins and fields, while django-filter specializes in creating powerful and flexible querysets for filtering data. django-model-utils excels in model-level enhancements, whereas django-filter is more suited for query-level filtering and API integrations. The choice between the two depends on the specific needs of your project, with django-model-utils being more general-purpose and django-filter focusing on advanced filtering capabilities.

This is a repository for collecting global custom management extensions for the Django Framework.

Pros of django-extensions

  • Broader scope with a wide range of management commands and utilities
  • Includes development tools like shell_plus and runserver_plus
  • Offers database schema visualization and GraphViz integration

Cons of django-extensions

  • May include unnecessary features for projects only needing filtering
  • Larger codebase and potential performance impact
  • Less focused on specific filtering functionality

Code Comparison

django-extensions (shell_plus example):

python manage.py shell_plus
# Imports all models and provides an enhanced shell environment

django-filter (basic filter usage):

from django_filters import FilterSet

class ProductFilter(FilterSet):
    class Meta:
        model = Product
        fields = ['name', 'price', 'category']

Summary

django-extensions offers a broader set of tools and utilities for Django development, including enhanced shell and runserver commands. It's more suitable for projects requiring various development aids. django-filter, on the other hand, focuses specifically on providing powerful filtering capabilities for Django querysets. Choose django-extensions for a comprehensive toolkit or django-filter for specialized filtering functionality.

Silky smooth profiling for Django

Pros of django-silk

  • Provides detailed profiling and inspection of HTTP requests and database queries
  • Offers a user-friendly web interface for analyzing performance data
  • Includes real-time monitoring capabilities for live debugging

Cons of django-silk

  • May introduce performance overhead in production environments
  • Requires more setup and configuration compared to django-filter
  • Limited to request/response profiling, unlike django-filter's broader data filtering capabilities

Code Comparison

django-silk:

from silk.profiling.profiler import silk_profile

@silk_profile(name='View Blog Post')
def post_detail(request, post_id):
    post = Post.objects.get(id=post_id)
    return render(request, 'post_detail.html', {'post': post})

django-filter:

import django_filters

class PostFilter(django_filters.FilterSet):
    title = django_filters.CharFilter(lookup_expr='icontains')
    author = django_filters.CharFilter(lookup_expr='icontains')

    class Meta:
        model = Post
        fields = ['title', 'author']

While django-silk focuses on profiling and performance analysis, django-filter specializes in data filtering and querying. django-silk provides detailed insights into request processing and database operations, making it valuable for debugging and optimization. On the other hand, django-filter offers a more straightforward approach to filtering querysets based on user input, which is particularly useful for search and list views in Django applications.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Django Filter

Django-filter is a reusable Django application allowing users to declaratively add dynamic QuerySet filtering from URL parameters.

Full documentation on read the docs_.

.. image:: https://raw.githubusercontent.com/carltongibson/django-filter/python-coverage-comment-action-data/badge.svg :target: https://github.com/carltongibson/django-filter/tree/python-coverage-comment-action-data

.. image:: https://badge.fury.io/py/django-filter.svg :target: http://badge.fury.io/py/django-filter

Versioning and stability policy

Django-Filter is a mature and stable package. It uses a two-part CalVer versioning scheme, such as 21.1. The first number is the year. The second is the release number within that year.

On an on-going basis, Django-Filter aims to support all current Django versions, the matching current Python versions, and the latest version of Django REST Framework.

Please see:

  • Status of supported Python versions <https://devguide.python.org/versions/#supported-versions>_
  • List of supported Django versions <https://www.djangoproject.com/download/#supported-versions>_

Support for Python and Django versions will be dropped when they reach end-of-life. Support for Python versions will be dropped when they reach end-of-life, even when still supported by a current version of Django.

Other breaking changes are rare. Where required, every effort will be made to apply a "Year plus two" deprecation period. For example, a change initially introduced in 23.x would offer a fallback where feasible and finally be removed in 25.1. Where fallbacks are not feasible, breaking changes without deprecation will be called out in the release notes.

Installation

Install using pip:

.. code-block:: sh

pip install django-filter

Then add 'django_filters' to your INSTALLED_APPS.

.. code-block:: python

INSTALLED_APPS = [
    ...
    'django_filters',
]

Usage

Django-filter can be used for generating interfaces similar to the Django admin's list_filter interface. It has an API very similar to Django's ModelForms. For example, if you had a Product model you could have a filterset for it with the code:

.. code-block:: python

import django_filters

class ProductFilter(django_filters.FilterSet):
    class Meta:
        model = Product
        fields = ['name', 'price', 'manufacturer']

And then in your view you could do:

.. code-block:: python

def product_list(request):
    filter = ProductFilter(request.GET, queryset=Product.objects.all())
    return render(request, 'my_app/template.html', {'filter': filter})

Usage with Django REST Framework

Django-filter provides a custom FilterSet and filter backend for use with Django REST Framework.

To use this adjust your import to use django_filters.rest_framework.FilterSet.

.. code-block:: python

from django_filters import rest_framework as filters

class ProductFilter(filters.FilterSet):
    class Meta:
        model = Product
        fields = ('category', 'in_stock')

For more details see the DRF integration docs_.

Support

If you need help you can start a discussion. For commercial support, please contact Carlton Gibson via his website <https://noumenal.es/>.

.. _discussion: https://github.com/carltongibson/django-filter/discussions .. _read the docs: https://django-filter.readthedocs.io/en/main/ .. _DRF integration docs: https://django-filter.readthedocs.io/en/stable/guide/rest_framework.html