Closes #21257: Introduce & adopt MultiValueContentTypeFilter (#21417)

This commit is contained in:
Jeremy Stretch
2026-02-13 05:24:36 -05:00
committed by GitHub
parent 76fd3e3c61
commit dc738c7102
21 changed files with 105 additions and 78 deletions

View File

@@ -1,6 +1,7 @@
import django_filters
from django import forms
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ValidationError
from django_filters.constants import EMPTY_VALUES
from drf_spectacular.types import OpenApiTypes
@@ -10,6 +11,7 @@ __all__ = (
'ContentTypeFilter',
'MultiValueArrayFilter',
'MultiValueCharFilter',
'MultiValueContentTypeFilter',
'MultiValueDateFilter',
'MultiValueDateTimeFilter',
'MultiValueDecimalFilter',
@@ -171,3 +173,27 @@ class ContentTypeFilter(django_filters.CharFilter):
f'{self.field_name}__model': model
}
)
class MultiValueContentTypeFilter(MultiValueCharFilter):
"""
A multi-value version of ContentTypeFilter.
"""
def filter(self, qs, value):
if value in EMPTY_VALUES:
return qs
content_types = []
for key in value:
try:
app_label, model = key.lower().split('.')
ct = ContentType.objects.get_by_natural_key(app_label, model)
content_types.append(ct)
except (ValueError, ContentType.DoesNotExist):
continue
return qs.filter(
**{
f'{self.field_name}__in': content_types,
}
)

View File

@@ -10,7 +10,7 @@ from mptt.models import MPTTModel
from taggit.managers import TaggableManager
from extras.filters import TagFilter
from utilities.filters import ContentTypeFilter, TreeNodeMultipleChoiceFilter
from utilities.filters import MultiValueContentTypeFilter, TreeNodeMultipleChoiceFilter
__all__ = (
'BaseFilterSetTests',
@@ -75,7 +75,7 @@ class BaseFilterSetTests:
# Standardize on object_type for filter name even though it's technically a ContentType
filter_name = 'object_type'
return [
(filter_name, ContentTypeFilter),
(filter_name, MultiValueContentTypeFilter),
(f'{filter_name}_id', django_filters.ModelMultipleChoiceFilter),
]