Django Filter 标志

Django Filter

组织
CodeAtCode
django-filter

Use when filtering Django querysets - FilterSet, custom filters, Django REST Framework integration, explicit fields

概览

发布者CodeAtCode
代码仓库oss-ai-skills
技能名称django-filter
星标数
30
复刻数
3
附带文件
仅含指令
许可协议GPL-3.0
链接
  • Markdown 格式的指令

    模型按需加载的 SKILL.md 文件,因此只有在请求确实匹配时才会消耗 Token。

  • 兼容任何大语言模型

    AI 技能采用纯 Markdown,而非特定提供商的代码,因此可搭配 GPT、Claude、Gemini、Grok 或本地模型使用。

  • 指令自成一体

    模型所需的一切都包含在指令中,无需同步额外文件。

  • 开源

    由 CodeAtCode 发布于 GitHub。请在安装前查看源内容。

安装

在 TypingMind 中安装 Django Filter AI 技能,即可搭配任意大语言模型使用;也可以将其放入其他支持读取 SKILL.md 的智能体中。

1

安装到 TypingMind

TypingMind 可直接从 GitHub 文件夹安装技能:读取 SKILL.md,打包资源文件,并将结果保存在本地。

  1. 打开应用,前往“插件 → 技能”。
  2. 选择“从 GitHub 安装”。
  3. 粘贴下方的技能文件夹 URL 并确认。
    https://github.com/CodeAtCode/oss-ai-skills/tree/master/frameworks/django-filter
  4. 请在每个需要使用该技能的聊天中启用它。
依次选择“插件 → 技能 → 添加技能 → 从 GitHub URL 导入”,然后粘贴文件夹 URL 并点击“继续”。
2

安装到其他智能体

任何支持 Agent Skills 格式的智能体都可以使用此技能,只需将文件夹复制到该智能体的技能目录中。

Claude Code — .claude/skills
git clone --depth 1 https://github.com/CodeAtCode/oss-ai-skills.git /tmp/oss-ai-skills
mkdir -p .claude/skills
cp -r /tmp/oss-ai-skills/frameworks/django-filter .claude/skills/django-filter
复制后,请重启 Claude Code,以加载新技能。

在 TypingMind 中使用此技能

在任意 TypingMind 聊天中启用 Django Filter,后续即可交由模型处理。技能的名称和描述会放在系统提示词中,一旦请求匹配,模型就会自动加载完整指令,无需您手动调用,且在实际使用前不会消耗 Token。

一旦请求与技能匹配,模型就会自动加载 Django Filter。

兼容任何 AI 模型

AI 技能是纯 Markdown 指令,而非特定提供商的代码,因此 Django Filter 不局限于最初适配的模型。只需在 TypingMind 中安装一次,即可搭配 GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 或您自行运行的本地模型使用,全程使用您自己的 API 密钥。

  • 仅在需要时加载

    系统提示词中仅包含技能名称和描述。首次遇到匹配的请求时才会获取指令,因此未使用的技能不会产生额外费用。

  • 在聊天中切换模型

    技能是指令而非代码,因此切换模型不会导致技能失效,新模型会读取同一个 SKILL.md。

技能指令

这是模型会加载的 SKILL.md 内容。请在安装前阅读,因为技能就是模型将遵循的指令。

Objective: Use this skill to prevent validation gaps, query injection, and N+1 filter inefficiency in Django filtering by enforcing declarative FilterSet usage, explicit field declaration, and queryset optimization.

django-filter

Django filtering library for dynamically filtering querysets, with full Django REST Framework integration.

Overview

django-filter provides a declarative way to filter querysets based on URL query parameters.

  • Declarative - Define filters as Python classes because manual query param parsing leads to validation gaps
  • DRF Integration - Seamless Django REST Framework support for auto-generated OpenAPI schemas
  • Flexible - Custom filter backends and fields when built-in lookups don't match query patterns
  • Auto-generation - FilterSet from Django models to avoid duplicating field definitions

Installation

bash
pip install django-filter

# With DRF integration
pip install django-filter djangorestframework

Add to INSTALLED_APPS:

python
INSTALLED_APPS = [
    'django_filters',
]

Basic FilterSet Pattern

python
# filters.py
import django_filters
from .models import Product

class ProductFilter(django_filters.FilterSet):
    # Range filters (min/max naming convention)
    price_min = django_filters.NumberFilter(field_name='price', lookup_expr='gte')
    price_max = django_filters.NumberFilter(field_name='price', lookup_expr='lte')
    
    # Text search
    name = django_filters.CharFilter(field_name='name', lookup_expr='icontains')
    
    # Boolean filter
    in_stock = django_filters.BooleanFilter(method='filter_in_stock')
    
    # Multiple selection (comma-separated values)
    categories = django_filters.CharFilter(field_name='category__slug', lookup_expr='in')
    
    # Date range
    created_after = django_filters.DateFilter(field_name='created_at', lookup_expr='gte')
    
    # Ordering
    order_by = django_filters.OrderingFilter(
        fields=[('price', 'price'), ('created_at', 'created_at'), ('name', 'name')]
    )

    class Meta:
        model = Product
        fields = '__all__'  # Django 6.0+: must be string '__all__' or explicit list

    def filter_in_stock(self, queryset, name, value):
        if value:
            return queryset.filter(stock__gt=0)
        return queryset

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

Django 6.0 Breaking Change

The fields attribute requires explicit __all__:

python
class UserFilter(FilterSet):
    class Meta:
        model = User
        fields = '__all__'  # String, not list

Using fields = [] without __all__ raises an error in Django 6.0+.


Filter Type Selection

Choose filter types based on query shape, not field type. See django-filter field documentation for the full API.

Query shapeFilter typeExample
Exact matchCharFilter / NumberFiltercategory = CharFilter()
Multiple valuesCharFilter with lookup_expr='in'ids = CharFilter(lookup_expr='in')
Range (min/max)Two separate filtersprice_min, price_max
Date rangeDateFromToRangeFilterdate_range = DateFromToRangeFilter()
Relational (FK/M2M)Filter on related fieldauthor__name = CharFilter()
Custom logicFilter with method=status = Filter(method='filter_status')

Avoid enumerating all 12+ filter types — focus on the lookup expressions you actually need: exact, icontains, gt, gte, lt, lte, in, isnull.


Composable QuerySet Methods

When filtering is driven by code paths rather than user-supplied query params, define a custom QuerySet with one method per WHERE clause. The view reads like a sentence, and each method is independently testable.

python
from django.db import models
from django.utils import timezone

class EventQuerySet(models.QuerySet):
    def approved(self):
        return self.filter(approved_at__isnull=False)

    def future(self):
        today = timezone.localdate()
        return self.filter(end__gt=self._midnight(today))

    def _midnight(self, date):
        return timezone.datetime(date.year, date.month, date.day, tzinfo=timezone.utc)

    def with_tags(self, tags):
        if not tags:
            return self
        return self.filter(tags__name__in=tags).distinct()

    def is_free(self, free):
        if free is None:
            return self
        return self.filter(price=0) if free else self

    def for_tab(self, tab):
        if tab == 'featured':
            return self.filter(featured=True)
        if tab == 'popular':
            return self.filter(views__gte=100)
        return self

class Event(models.Model):
    objects = EventQuerySet.as_manager()
    # ...

Usage in a view — each method returns a queryset, so they chain naturally:

python
def event_list(request, tab):
    qs = (
        Event.objects.approved()
        .for_tab(tab)
        .with_tags(request.GET.getlist('tags'))
        .is_free(request.GET.get('free') == 'true')
    )
    return render(request, 'events/list.html', {'events': qs})

Guidelines for QuerySet methods

  • Return self (not None) when the filter is a no-op, so chains never break.
  • Guard each method against its argument being empty/None — callers should not have to branch before calling.
  • Keep methods single-purpose; compose in the view rather than adding flags.

FilterSet Composition

Combining FilterSets with &

Combine multiple FilterSet classes to create composite filters:

python
class BaseProductFilter(django_filters.FilterSet):
    """Common filters used across multiple views."""
    search = django_filters.CharFilter(method='filter_search')
    category = django_filters.ModelChoiceFilter(
        field_name='category',
        queryset=Category.objects.active()
    )

    class Meta:
        model = Product
        fields = []

    def filter_search(self, queryset, name, value):
        if not value:
            return queryset
        return queryset.filter(
            models.Q(name__icontains=value) |
            models.Q(description__icontains=value)
        )

class PriceFilter(django_filters.FilterSet):
    price_min = django_filters.NumberFilter(field_name='price', lookup_expr='gte')
    price_max = django_filters.NumberFilter(field_name='price', lookup_expr='lte')
    on_sale = django_filters.BooleanFilter(method='filter_on_sale')

    class Meta:
        model = Product
        fields = []

    def filter_on_sale(self, queryset, name, value):
        if value:
            return queryset.filter(discount__gt=0)
        return queryset

# Combine filters
ProductFilter = BaseProductFilter & PriceFilter

Failure mode: Without composition, you either duplicate filter definitions or create bloated monolithic FilterSet classes. The & operator merges filters cleanly.

Subclassing for shared base filters

python
class BaseFilter(django_filters.FilterSet):
    """Base class with filters shared across multiple FilterSets."""
    created_after = django_filters.DateFilter(field_name='created_at', lookup_expr='gte')
    created_before = django_filters.DateFilter(field_name='created_at', lookup_expr='lte')
    ordering = django_filters.OrderingFilter(
        fields=['created_at', 'updated_at', 'name']
    )

    class Meta:
        model = None  # Subclasses must define Meta.model
        fields = []

class ProductFilter(BaseFilter):
    class Meta:
        model = Product
        fields = ['category', 'is_active']

class OrderFilter(BaseFilter):
    class Meta:
        model = Order
        fields = ['status', 'customer']

Failure mode: Duplicating date range and ordering filters across multiple FilterSet classes leads to drift when you add a new field to one but forget another.

Using @property for computed filters

python
class ProductFilter(django_filters.FilterSet):
    price_min = django_filters.NumberFilter()
    price_max = django_filters.NumberFilter()

    class Meta:
        model = Product
        fields = []

    @property
    def is_price_range_valid(self):
        """Check if both min and max are provided and valid."""
        price_min = self.data.get('price_min')
        price_max = self.data.get('price_max')
        if price_min and price_max:
            return float(price_min) <= float(price_max)
        return True

    @property
    def qs(self):
        qs = super().qs
        # Access computed property to trigger validation
        if not self.is_price_range_valid:
            # Return empty queryset or raise error
            return qs.none()
        return qs

Failure mode: Trying to validate cross-field constraints in __init__ fails because filters haven't been instantiated yet. Use @property on qs to validate after filter application.

Overriding get_queryset() for cross-field logic

python
class ProductFilter(django_filters.FilterSet):
    min_price = django_filters.NumberFilter(field_name='price', lookup_expr='gte')
    max_price = django_filters.NumberFilter(field_name='price', lookup_expr='lte')
    category = django_filters.CharFilter()

    class Meta:
        model = Product
        fields = []

    def get_queryset(self):
        """Access other filter values for cross-field logic."""
        qs = super().get_queryset()
        
        # Example: filter based on relationship between fields
        min_price = self.data.get('min_price')
        max_price = self.data.get('max_price')
        
        if min_price and max_price:
            # Custom logic: ensure price is within 10% of midpoint
            midpoint = (float(min_price) + float(max_price)) / 2
            tolerance = midpoint * 0.1
            qs = qs.filter(price__gte=midpoint - tolerance, price__lte=midpoint + tolerance)
        
        return qs

Failure mode: FilterSet re-runs get_queryset() per request — there's no caching of the base queryset. If your get_queryset() performs expensive operations, cache the result or move logic to the view.

distinct() for ManyToMany traversals

python
class ProductFilter(django_filters.FilterSet):
    tags = django_filters.CharFilter(field_name='tags__name', lookup_expr='in')
    categories = django_filters.CharFilter(field_name='category__slug', lookup_expr='in')

    class Meta:
        model = Product
        fields = ['tags', 'categories']
        # Enable distinct to avoid duplicate rows from M2M joins
        # Note: django-filter doesn't auto-add distinct; you must handle it

In the view:

python
def product_list(request):
    filter = ProductFilter(request.GET, queryset=Product.objects.all())
    qs = filter.qs.distinct()  # Required for M2M filters
    return render(request, 'products.html', {'products': qs})

Failure mode: Without distinct(), filtering on multiple M2M relationships produces duplicate rows (Cartesian product of joins).


Decision: django-filter vs plain query params vs manual filtering

Use django-filter when

  • You need DRF integration (automatic filter schema, OpenAPI docs)
  • Filters are user-facing and dynamic (users can combine any filter)
  • You have 10+ filter parameters or complex cross-field logic
  • Multiple views share the same filter set
  • You want validation of filter values (type coercion, range checks)

Use plain request.GET when

  • You have 2-3 stable parameters (e.g., page, limit, sort)
  • The API is internal with controlled consumers
  • You need full control over query construction
  • The threshold: hand-written request.GET handling is simpler for ≤3 params
python
def product_list(request):
    page = int(request.GET.get('page', 1))
    limit = min(int(request.GET.get('limit', 20)), 100)  # Cap at 100
    sort = request.GET.get('sort', 'created_at')
    
    if sort not in ['created_at', 'price', 'name']:
        sort = 'created_at'  # Whitelist validation
    
    qs = Product.objects.all().order_by(sort)[(page-1)*limit:page*limit]
    return render(request, 'products.html', {'products': qs})

When django-filter is overkill

  • Public API with a handful of stable params — manual handling is clearer
  • Filters that depend on session/auth state — put logic in get_queryset()
  • Complex business logic — use QuerySet methods instead of filters

Correctness & Performance

distinct() on ManyToMany traversals

When filtering on M2M relationships, JOINs produce duplicate rows:

python
# Without distinct: products with 3 tags appear 3 times
qs = Product.objects.filter(tags__name__in=['sale', 'new'])

# With distinct: each product appears once
qs = Product.objects.filter(tags__name__in=['sale', 'new']).distinct()

Warning: distinct() without arguments uses all fields. If you need to order by a filtered field, use distinct('field_name') (PostgreSQL only) or restructure the query.

Indexing filtered columns

A filter on an unindexed column is a table scan:

python
class Product(models.Model):
    name = models.CharField(max_length=255, db_index=True)  # Index on filter field
    price = models.DecimalField(max_digits=10, 2, db_index=True)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    
    class Meta:
        indexes = [
            models.Index(fields=['-created_at']),  # For ordering
            models.Index(fields=['category', '-created_at']),  # Composite
        ]

Use EXPLAIN to verify index usage on slow filters.

Bounding __in with user-supplied lists

python
# Dangerous: unbounded list from user input
ids = request.GET.getlist('ids')
Product.objects.filter(id__in=ids)  # Could be millions of rows

# Safe: cap the list length
MAX_IDS = 100
ids = request.GET.getlist('ids')[:MAX_IDS]
Product.objects.filter(id__in=ids)

Failure mode: id__in with 10,000 values creates a massive SQL IN clause, causing query timeouts.

FilterSet re-runs get_queryset() per request

python
class ProductViewSet(viewsets.ModelViewSet):
    filterset_class = ProductFilter
    
    def get_queryset(self):
        # This runs EVERY request, not just once
        return Product.objects.select_related('category')

Failure mode: Assuming get_queryset() is cached and putting expensive operations there (e.g., calling an external API). Cache explicitly if needed:

python
from django.core.cache import cache

def get_queryset(self):
    cache_key = 'product_base_qs'
    qs = cache.get(cache_key)
    if qs is None:
        qs = Product.objects.select_related('category')
        cache.set(cache_key, qs, timeout=300)
    return qs

Django REST Framework Integration

Basic ViewSet setup

python
from rest_framework import viewsets
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import filters
from .models import Product
from .filters import ProductFilter

class ProductViewSet(viewsets.ModelViewSet):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer
    
    filter_backends = [DjangoFilterBackend, filters.OrderingFilter]
    filterset_class = ProductFilter
    ordering_fields = ['price', 'created_at']
    ordering = ['-created_at']

Ordering pitfall: OrderingFilter vs FilterSet ordering

OrderingFilter (from DRF) and FilterSet ordering are separate:

python
class ProductFilter(django_filters.FilterSet):
    # This creates an 'order_by' filter param
    order_by = django_filters.OrderingFilter(
        fields=['price', 'created_at']
    )

    class Meta:
        model = Product
        fields = []

class ProductViewSet(viewsets.ModelViewSet):
    filter_backends = [DjangoFilterBackend, filters.OrderingFilter]
    filterset_class = ProductFilter
    # ordering_fields applies to DRF's OrderingFilter, NOT FilterSet
    ordering_fields = ['price', 'created_at']

Failure mode: Using both OrderingFilter in filter_backends AND an OrderingFilter field in your FilterSet creates conflicting ordering behavior. Pick one:

  • Use FilterSet.ordering for filter-param-based ordering (user types ?order_by=-price)
  • Use OrderingFilter in filter_backends for header-based ordering (user sends Order: -price)

URL Patterns

bash
# Basic filtering
GET /api/products/?category=1
GET /api/products/?price_min=10&price_max=100

# Text search
GET /api/products/?name__icontains=laptop

# Multiple values (comma-separated)
GET /api/products/?categories=electronics,books

# Date range
GET /api/products/?created_after=2024-01-01

# Ordering
GET /api/products/?order_by=-price
GET /api/products/?ordering=-price  # DRF OrderingFilter

Common Pitfalls

S silently ignoring unknown query parameters

django-filter ignores parameters not defined in your FilterSet:

python
class ProductFilter(django_filters.FilterSet):
    price_min = django_filters.NumberFilter()
    
    class Meta:
        model = Product
        fields = []

# GET /api/products/?unknown_param=123 → silently ignored

Fix: Validate with strict=True (django-filter 4.0+):

python
class ProductFilter(django_filters.FilterSet):
    class Meta:
        model = Product
        fields = []
        strict = True  # Raise error on unknown params

Not exposing all model fields accidentally

python
class Meta:
    model = Product
    fields = '__all__'  # Exposes EVERY field — often unintended

Fix: Be explicit:

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

References

常见问题

Django Filter AI 技能有什么作用?

Use when filtering Django querysets - FilterSet, custom filters, Django REST Framework integration, explicit fields

为什么在 TypingMind 中使用 Django Filter?

因为您只需安装一次,就能搭配任何模型使用。Django Filter 采用纯 Markdown 格式,而非特定提供商专用的代码,因此同一技能可用于 GPT-5、Claude、Gemini、Grok 或本地模型,甚至可以在聊天中途切换模型,而不会影响技能正常使用。TypingMind 使用您自己的 API 密钥,因此您直接向提供商付费,而不是按席位订阅;您的技能和聊天记录也都保留在您自己的存储空间中。

如何在 TypingMind 中安装 Django Filter?

在 TypingMind 中打开“插件 → 技能 → 从 GitHub 安装”,然后粘贴 https://github.com/CodeAtCode/oss-ai-skills/tree/master/frameworks/django-filter。TypingMind 会读取其中的 SKILL.md,并将其安装为技能,供您在各个聊天中按需启用。

哪些 AI 模型可以使用 Django Filter?

您在 TypingMind 中连接的任何模型都可以。AI 技能采用纯 Markdown 指令,而非特定提供商专用的代码,因此 GPT、Claude、Gemini、Grok 和本地模型都能在请求匹配时加载此技能。

Django Filter 可以搭配多少个 AI 模型使用?

数量不限。只要模型支持技能,您就可以搭配 Django Filter 使用,包括 GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 等,都可在 TypingMind 中使用您自己的 API 密钥接入。

Django Filter AI 技能免费吗?

是的。该技能源自 CodeAtCode 在 GitHub 上以 GPL-3.0 许可证发布的项目。您只需向自己的 AI 提供商支付所用 Token 的费用。

什么是 AI 技能?

AI 技能是一组可复用的指令,用于教会 AI 模型完成某项特定任务。它遵循开放的 Agent Skills 格式:包含名称和描述的 SKILL.md 文件,以及模型可能需要的脚本、模板或参考文件。模型仅在您的请求与技能匹配时才会读取这些指令,因此已安装的技能在使用前不会产生任何费用。

AI 技能与插件或 MCP 服务器有何不同?

插件或 MCP 服务器为模型提供可调用的新工具,也就是在某处运行并返回结果的代码。AI 技能则为模型提供知识和流程:如何处理任务、遵循哪些步骤,以及怎样的输出才算优质。技能采用纯 Markdown 格式,因此不需要服务器、API 密钥或运行时环境,并且适用于任何模型。

查看全部

立即创建您自己的 AI 工作区

订阅我们的电子简报,获取新功能和后续赠奖活动的通知 👇