Skip to content

Commit

Permalink
feat(generic): add a collections filter
Browse files Browse the repository at this point in the history
  • Loading branch information
b1rger committed Jan 27, 2025
1 parent 6e9b306 commit 250034b
Showing 1 changed file with 51 additions and 0 deletions.
51 changes: 51 additions & 0 deletions apis_core/generic/filtersets.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,50 @@
import logging
from django.apps import apps
from django import forms
import django_filters
from django_filters.filterset import FilterSet
from django.contrib.contenttypes.models import ContentType

from .forms import GenericFilterSetForm

logger = logging.getLogger(__name__)


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


class IncludeExcludeField(forms.MultiValueField):
def __init__(self, field, lookup_choices, *args, **kwargs):



class CollectionsFilter(django_filters.filters.QuerySetRequestMixin, django_filters.LookupChoiceFilter):
field_class = django_filters.fields.ModelMultipleChoiceField

def filter(self, queryset, lookup):
if not lookup:
return super().filter(queryset, None)
if lookup:
print(lookup.lookup_expr)
print(lookup.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=lookup.value).values("object_id")
print(scco)
return queryset.filter(id__in=scco)
except LookupError as e:
logger.debug("Not filtering for collections: %s", e)


class GenericFilterSet(FilterSet):
"""
Expand All @@ -12,3 +55,11 @@ class GenericFilterSet(FilterSet):

class Meta:
form = GenericFilterSetForm

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
try:
skoscollection = apps.get_model("collections.SkosCollection")
self.filters["collections"] = CollectionsFilter(queryset=skoscollection.objects.all(), lookup_choices = [("exclude"), ("include")])
except LookupError as e:
logger.debug("Not adding collections filter to form: %s", e)

0 comments on commit 250034b

Please sign in to comment.