Debian Codegraph @

src/polymorphic/admin/filters.py

raw
1 from __future__ import annotations
2
3 from collections.abc import Iterable
4 from typing import Any, cast
5
6 from django.contrib import admin
7 from django.core.exceptions import PermissionDenied
8 from django.db.models import QuerySet
9 from django.http import HttpRequest
10 from django.utils.translation import gettext_lazy as _
11
12 from .parentadmin import PolymorphicParentModelAdmin
13
14
15 class PolymorphicChildModelFilter(admin.SimpleListFilter):
16 """
17 An admin list filter for the PolymorphicParentModelAdmin which enables
18 filtering by its child models.
19
20 This can be used in the parent admin:
21
22 .. code-block:: python
23
24 list_filter = (PolymorphicChildModelFilter,)
25 """
26
27 title: str = _("Type") # type: ignore[assignment]
28 parameter_name: str = "polymorphic_ctype"
29
30 def lookups( # type: ignore[override]
31 self, request: HttpRequest, model_admin: PolymorphicParentModelAdmin
32 ) -> Iterable[tuple[str, str]]:
33 return cast(
34 Iterable[tuple[str, str]], model_admin.get_child_type_choices(request, "change")
35 )
36
37 def queryset(self, request: HttpRequest, queryset: QuerySet[Any]) -> QuerySet[Any]:
38 raw_value = self.value()
39 if not raw_value:
40 return queryset
41 try:
42 value = int(raw_value)
43 except TypeError:
44 value = None
45 if value:
46 # ensure the content type is allowed
47 for choice_value, _ in self.lookup_choices: # noqa: F402
48 if int(choice_value) == value:
49 return queryset.filter(polymorphic_ctype_id=choice_value)
50 raise PermissionDenied(
51 f'Invalid ContentType "{value}". It must be registered as child model.'
52 )
53 return queryset