-
-
Notifications
You must be signed in to change notification settings - Fork 0
Use Filterset Factory in Project and Sample Views #1868
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
Open
nozomione
wants to merge
8
commits into
dev
Choose a base branch
from
nozomone/1849-refactor-project-sample-endpoints
base: dev
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+239
−77
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
a1fb632
add a FilterSet factory, filter.py module, to the project root (boots…
nozomione 5723ee3
(edit) utilize the bootstrapped FilterSet factory method in both the …
nozomione 4a6b1d6
(fix) remove unused imports
nozomione e13b690
(fix indent) make sure to retun a queryset after all terms iteration
nozomione de36fa0
(fix) include custom lookup fileds (e.g., for relationship lookup fie…
nozomione 1d4434b
(edit) rename include_fields to auto_fields and add a new extra_field…
nozomione 931c8a0
add a test for the filter module
nozomione ae7bec9
(fix) clean up the 'diagnosis' field from the expected_fields (no lon…
nozomione File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,89 @@ | ||
| from django.contrib.postgres.fields import ArrayField | ||
| from django.db import models | ||
|
|
||
| import django_filters | ||
| from django_filters import rest_framework as filters | ||
|
|
||
| # Lookup expressions per field type | ||
| FILTER_LOOKUPS = { | ||
| models.BigIntegerField: ["exact", "gte", "lte", "gt", "lt", "in"], | ||
| models.BooleanField: ["exact"], | ||
| models.CharField: ["exact", "icontains", "istartswith"], | ||
| models.DateTimeField: ["exact", "gte", "lte", "date"], | ||
| models.EmailField: ["exact", "icontains", "istartswith"], | ||
| models.IntegerField: ["exact", "gte", "lte", "gt", "lt", "in"], | ||
| models.JSONField: ["exact", "in"], | ||
| models.PositiveIntegerField: ["exact", "gte", "lte", "gt", "lt", "in"], | ||
| models.TextField: ["exact", "icontains"], | ||
| } | ||
|
|
||
|
|
||
| # Custom filter for Postgres ArrayFields | ||
| class ArrayFieldContainsFilter(django_filters.BaseInFilter, django_filters.CharFilter): | ||
| """ | ||
| Accepts comma-separated values and applies icontains per term (AND logic). | ||
| e.g. ?diagnoses=Neuroblastoma,Glioma matches projects containing both. | ||
| NOTE: Swap the loop for Q objects if you want OR logic instead. | ||
| """ | ||
|
|
||
| def filter(self, qs, value): | ||
| if not value: | ||
| return qs | ||
| for term in value: | ||
| qs = qs.filter(**{f"{self.field_name}__icontains": term.strip()}) | ||
| return qs | ||
|
|
||
|
|
||
| # Filterset Factory | ||
| def build_auto_filterset( | ||
| model, | ||
| auto_fields: list[str] = None, | ||
| extra_fields: dict[str, list[str]] = None, | ||
| extra_filters: dict = None, | ||
| ): | ||
| """ | ||
| Introspects a model and builds a FilterSet with sensible lookup expressions | ||
| per field type. ArrayFields get icontains via ArrayFieldContainsFilter. | ||
| Args: | ||
| model: The Django model class to build a FilterSet for. | ||
| auto_fields: Optional allowlist of field names. If omitted, all | ||
| supported field types are included. Always use this | ||
| to keep your public API surface intentional. | ||
| extra_fields: Additional model fields included in the public API | ||
| e.g. {"project__scpca_id": ["exact"]}. | ||
| extra_filters: Optional dict of additional filter instances to mix in, | ||
| excluded from the public API | ||
| e.g. {"in_stock": MyCustomFilter(...)}. | ||
| """ | ||
|
|
||
| declared_filters = {} | ||
| meta_fields = {} | ||
|
|
||
| for field in model._meta.get_fields(): | ||
| if field.is_relation and (field.one_to_many or field.many_to_many): | ||
| # Skip reverse relations and ManyToMany | ||
| continue | ||
| if auto_fields and field.name not in auto_fields: | ||
| continue | ||
|
|
||
| # ArrayField: use custom filter, one filter per field | ||
| if isinstance(field, ArrayField): | ||
| declared_filters[field.name] = ArrayFieldContainsFilter(field_name=field.name) | ||
| continue | ||
|
|
||
| # Standard field types: use dict-style meta fields for multi-lookup support | ||
| for field_type, lookups in FILTER_LOOKUPS.items(): | ||
| if isinstance(field, field_type): | ||
| meta_fields[field.name] = lookups | ||
| break | ||
|
|
||
| if extra_fields: | ||
| meta_fields.update(extra_fields) | ||
|
|
||
| if extra_filters: | ||
| declared_filters.update(extra_filters) | ||
|
|
||
| meta = type("Meta", (), {"model": model, "fields": meta_fields}) | ||
| attrs = {"Meta": meta, **declared_filters} | ||
|
|
||
| return type(f"{model.__name__}AutoFilterSet", (filters.FilterSet,), attrs) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,81 @@ | ||
| from django.test import TestCase | ||
|
|
||
| from scpca_portal import filter | ||
| from scpca_portal.filter import ArrayFieldContainsFilter | ||
| from scpca_portal.models import Sample | ||
|
|
||
|
|
||
| class FilterTest(TestCase): | ||
| @classmethod | ||
| def setUpTestData(cls): | ||
| cls.SampleFilterSet = filter.build_auto_filterset( | ||
| Sample, | ||
| auto_fields=[ | ||
| "scpca_id", # TextField | ||
| "has_cite_seq_data", # BooleanField | ||
| "technologies", # ArrayField | ||
| "sample_cell_count_estimate", # IntegerField | ||
| "updated_at", # DateTimeField | ||
| ], | ||
| extra_fields={"project__scpca_id": ["exact"]}, | ||
| ) | ||
|
|
||
| def test_all_included_fields(self): | ||
| actual_fields = self.SampleFilterSet.base_filters.keys() | ||
| expected_fields = [ | ||
| "scpca_id", | ||
| "has_cite_seq_data", | ||
| "technologies", | ||
| "sample_cell_count_estimate", | ||
| "updated_at", | ||
| # extra_fields | ||
| "project__scpca_id", | ||
| ] | ||
|
|
||
| for expected_field in expected_fields: | ||
| self.assertIn(expected_field, actual_fields) | ||
|
|
||
| def test_array_fields(self): | ||
| # Should be an instance of ArrayFieldContainsFilter | ||
| array_field_filter = self.SampleFilterSet.base_filters["technologies"] | ||
| self.assertIsInstance(array_field_filter, ArrayFieldContainsFilter) | ||
|
|
||
| def test_boolean_fields(self): | ||
| # Should support "exact" | ||
| actual_fields = self.SampleFilterSet.base_filters.keys() | ||
| expected_fields = ["has_cite_seq_data"] | ||
|
|
||
| for expected_field in expected_fields: | ||
| self.assertIn(expected_field, actual_fields) | ||
|
|
||
| def test_datetime_fields(self): | ||
| # Should support "exact", "gte", "lte", and "date" | ||
| actual_fields = self.SampleFilterSet.base_filters.keys() | ||
| expected_fields = ["updated_at", "updated_at__gte", "updated_at__lte", "updated_at__date"] | ||
|
|
||
| for expected_field in expected_fields: | ||
| self.assertIn(expected_field, actual_fields) | ||
|
|
||
| def test_integer_fields(self): | ||
| # Should support"exact", "gte", "lte", "gt", "lt", and "in" | ||
| actual_fields = self.SampleFilterSet.base_filters.keys() | ||
|
|
||
| expected_fields = [ | ||
| "sample_cell_count_estimate", | ||
| "sample_cell_count_estimate__gte", | ||
| "sample_cell_count_estimate__lte", | ||
| "sample_cell_count_estimate__gt", | ||
| "sample_cell_count_estimate__lt", | ||
| "sample_cell_count_estimate__in", | ||
| ] | ||
|
|
||
| for expected_field in expected_fields: | ||
| self.assertIn(expected_field, actual_fields) | ||
|
|
||
| def test_text_fields(self): | ||
| # Should support "exact", "icontains" | ||
| actual_fields = self.SampleFilterSet.base_filters.keys() | ||
| expected_fields = ["scpca_id", "scpca_id__icontains"] | ||
|
|
||
| for expected_field in expected_fields: | ||
| self.assertIn(expected_field, actual_fields) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.