Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(generic): add a collections filter #1567

Merged
merged 1 commit into from
Feb 5, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions apis_core/generic/filtersets.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,47 @@
import logging

import django_filters
from django.apps import apps
from django.contrib.contenttypes.models import ContentType
from django_filters.filterset import FilterSet

from apis_core.generic.forms.fields import IncludeExcludeField

from .forms import GenericFilterSetForm

logger = logging.getLogger(__name__)


class CollectionsFilter(django_filters.filters.ModelMultipleChoiceFilter):
"""
A simple filter for connections to collections. It provides an `include`/`exclude`
selector, which allows to define what the filter should do.
"""

@property
def field(self):
return IncludeExcludeField(super().field, required=self.extra["required"])

def filter(self, queryset, value):
value, include_exclude = value
if value:
content_type = ContentType.objects.get_for_model(queryset.model)
try:
skoscollectioncontentobject = apps.get_model(
"collections.SkosCollectionContentObject"
)
scco = skoscollectioncontentobject.objects.filter(
content_type=content_type, collection__in=value
).values("object_id")
match include_exclude:
case "include":
return queryset.filter(id__in=scco)
case "exclude":
return queryset.exclude(id__in=scco)
except LookupError as e:
logger.debug("Not filtering for collections: %s", e)
return queryset


class GenericFilterSet(FilterSet):
"""
Expand All @@ -12,3 +52,14 @@ class GenericFilterSet(FilterSet):

class Meta:
form = GenericFilterSetForm

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
try:
skoscollection = apps.get_model("collections.SkosCollection")
if skoscollection.objects.exists():
self.filters["collections"] = CollectionsFilter(
queryset=skoscollection.objects.all(),
)
except LookupError as e:
logger.debug("Not adding collections filter to form: %s", e)
29 changes: 28 additions & 1 deletion apis_core/generic/forms/fields.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from django.core.exceptions import ValidationError
from django.forms import ModelChoiceField
from django.forms import ChoiceField, ModelChoiceField, MultiValueField, MultiWidget
from django.utils.translation import gettext as _

from apis_core.utils.helpers import create_object_from_uri
Expand All @@ -16,3 +16,30 @@ def to_python(self, value):
params={"value": value, "exception": e},
)
return result or super().to_python(value)


class IncludeExcludeMultiWidget(MultiWidget):
template_name = "widgets/includeexclude_multiwidget.html"
use_fieldset = False

def decompress(self, value):
return [value, value]


class IncludeExcludeField(MultiValueField):
"""
This is a custom MultiValueField that adds a ChoiceField that only provides two
choices, namely `exclude` and `include`. It can be used for django-filter filters
to specify which action should be done with the filter.
"""

def __init__(self, field, *args, **kwargs):
fields = (
field,
ChoiceField(choices=[("include", "include"), ("exclude", "exclude")]),
)
kwargs["widget"] = IncludeExcludeMultiWidget(widgets=[f.widget for f in fields])
super().__init__(fields=fields, *args, **kwargs)

def compress(self, data_list):
return data_list
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<div class="row">
<div class="col">{% include widget.subwidgets.0.template_name with widget=widget.subwidgets.0 %}</div>
<div class="col-auto">{% include widget.subwidgets.1.template_name with widget=widget.subwidgets.1 %}</div>
</div>