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: support a initial (default) filter's value be a callable #56

Merged
merged 3 commits into from
Jun 21, 2024
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
15 changes: 5 additions & 10 deletions drf_kit/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,21 +26,17 @@ def __init__(self, model_klass, body, integrity_error):
super().__init__(message=message, code=self.status_code)

@abc.abstractmethod
def build_message(self) -> str:
...
def build_message(self) -> str: ... # fmt: skip

@abc.abstractmethod
def _parse_psql(self):
...
def _parse_psql(self): ... # fmt: skip

@abc.abstractmethod
def _parse_sqlite(self):
...
def _parse_sqlite(self): ... # fmt: skip

@classmethod
@abc.abstractmethod
def verify(cls, integrity_error: IntegrityError) -> bool:
...
def verify(cls, integrity_error: IntegrityError) -> bool: ... # fmt: skip

@property
def response(self):
Expand Down Expand Up @@ -194,8 +190,7 @@ def _clean(v):
values.append(value)
return keys, values, constraint_name

def _parse_sqlite(self):
...
def _parse_sqlite(self): ...

@classmethod
def verify(cls, integrity_error: IntegrityError) -> bool:
Expand Down
8 changes: 8 additions & 0 deletions drf_kit/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,8 @@ def __init__(self, *args, data=None, **kwargs):
initial = filter_obj.extra.get("initial", None)
if not data.get(name) and initial is not None:
data[name] = initial
if callable(initial):
data[name] = initial(request=kwargs["request"])

super().__init__(data, *args, **kwargs)

Expand All @@ -81,6 +83,12 @@ class _OpenChoiceField(MultipleChoiceField):
def valid_value(self, value):
return True

def clean(self, value):
# when the value is set by Field.initial, it turns into a list of lists because each
# field in the query parameters (set up at the Django view layer) defaults to being a list
value = value[0] if value and isinstance(value, list) and isinstance(value[0], list) else value
return super().clean(value)


class AnyOfFilter(MultipleChoiceFilter):
field_class = _OpenChoiceField
Expand Down
3 changes: 1 addition & 2 deletions drf_kit/managers/soft_delete_managers.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,5 +131,4 @@ class SoftDeleteOrderedManager(SoftDeleteManager):
queryset_class = SoftDeleteOrderedQueryset


class SoftDeleteAvailabilityManager(AvailabilityManager, SoftDeleteManager):
...
class SoftDeleteAvailabilityManager(AvailabilityManager, SoftDeleteManager): ... # fmt: skip
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ pytest-random-order = "*"

[tool.ruff]
line-length = 120
target-version = "py312"
target-version = "py311"

[tool.ruff.lint]
select = ["RUF", "I", "PL", "F", "COM", "UP", "DJ", "T10", "T20", "DTZ", "SIM", "TID", "PTH", "ERA", "TRY"]
Expand Down
20 changes: 20 additions & 0 deletions test_app/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,23 @@ class WizardFilterSet(filters.BaseFilterSet):
class Meta:
model = models.Wizard
fields = ["spell_name"]


class TrainingPitchFilterSet(filters.BaseFilterSet):
name = filters.AnyOfFilter(initial=["Poppins"])

class Meta:
model = models.TrainingPitch
fields = ["name"]


def get_default_is_active(request) -> int:
return 1


class BeastFilterSet(filters.BaseFilterSet):
is_active = filters.IntBooleanFilter(initial=get_default_is_active)

class Meta:
model = models.Beast
fields = ["is_active"]
17 changes: 17 additions & 0 deletions test_app/migrations/0012_beast_is_active.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Generated by Django 5.0.6 on 2024-06-21 13:24

from django.db import migrations, models


class Migration(migrations.Migration):
dependencies = [
("test_app", "0011_trainingpitch_reservation_and_more"),
]

operations = [
migrations.AddField(
model_name="beast",
name="is_active",
field=models.BooleanField(default=True),
),
]
1 change: 1 addition & 0 deletions test_app/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,7 @@ class Beast(SoftDeleteModel):
name = models.CharField(max_length=100)
age = models.IntegerField()
category = models.ForeignKey(to=BeastCategory, on_delete=models.CASCADE, null=True, related_name="beasts")
is_active = models.BooleanField(default=True)

class Meta(BaseModel.Meta):
constraints = [
Expand Down
6 changes: 6 additions & 0 deletions test_app/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -173,3 +173,9 @@ class Meta(serializers.BaseModelSerializer.Meta):
"pitch_id",
"period",
)


class TrainingPitchSerializer(serializers.BaseModelSerializer):
class Meta(serializers.BaseModelSerializer.Meta):
model = models.TrainingPitch
fields = ("id",)
36 changes: 36 additions & 0 deletions test_app/tests/tests_filter.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from drf_kit import filters
from drf_kit.tests import BaseApiTest
from test_app.tests.factories.beast_factories import BeastFactory
from test_app.tests.factories.teacher_factories import TeacherFactory
from test_app.tests.tests_base import HogwartsTestMixin

Expand Down Expand Up @@ -246,3 +247,38 @@ class TestAllOfFilter(BaseApiTest):
def test_raise_exception_when_created_alloffilter_with_conjoined_false(self):
with self.assertRaisesMessage(ValueError, "AllOfFilter must be conjoined=True"):
filters.AllOfFilter(conjoined=False)


class TestCallableInitialFilter(BaseApiTest):
url = "/beasts"

def test_filter_with_initial_values(self):
beasts = [
BeastFactory(is_active=True),
]

BeastFactory(is_active=False) # noise

response = self.client.get(self.url)

self.assertEqual(200, response.status_code)

results = response.json()["results"]
expected_ids = [b.pk for b in beasts]
result_ids = [r["id"] for r in results]
self.assertEqual(expected_ids, list(reversed(result_ids)))

def test_filter_overwrite_initial_filters(self):
beasts = [BeastFactory(is_active=False)]

# noise
BeastFactory(is_active=True)
BeastFactory(is_active=True)
response = self.client.get(self.url, data={"is_active": 0})

self.assertEqual(200, response.status_code)

results = response.json()["results"]
expected_ids = [b.pk for b in beasts]
result_ids = [r["id"] for r in results]
self.assertEqual(expected_ids, list(reversed(result_ids)))
13 changes: 13 additions & 0 deletions test_app/tests/tests_views/tests_filter_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from test_app.tests.factories.spell_cast_factories import CombatSpellCastFactory
from test_app.tests.factories.spell_factories import SpellFactory
from test_app.tests.factories.teacher_factories import TeacherFactory
from test_app.tests.factories.training_pitch_factories import TrainingPitchFactory
from test_app.tests.factories.wizard_factories import WizardFactory
from test_app.tests.tests_base import HogwartsTestMixin

Expand Down Expand Up @@ -70,6 +71,18 @@ def test_search_body_ordered(self):
self.assertResponseList(expected_items=expected_teachers, response=response)


class TestAnyOfFilter(BaseApiTest):
def test_with_initial_value(self):
pitch = TrainingPitchFactory(name="Poppins")
TrainingPitchFactory(name="Big House")

url = "/training-pitches"
response = self.client.get(url)
expected_ids = [pitch.pk]
result_ids = [r["id"] for r in response.json()["results"]]
self.assertEqual(expected_ids, result_ids)


class TestAllOfFilterView(HogwartsTestMixin, BaseApiTest):
url = "/wizards-custom-filter"

Expand Down
6 changes: 6 additions & 0 deletions test_app/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,4 +93,10 @@
"reservation",
)

router.register(
r"training-pitches",
views.TrainingPitchViewSet,
"training-pitches",
)

urlpatterns = router.urls
7 changes: 7 additions & 0 deletions test_app/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ class WandViewSet(NonDestructiveModelViewSet):
class BeastViewSet(ModelViewSet):
queryset = models.Beast.objects.all()
serializer_class = serializers.BeastSerializer
filterset_class = filters.BeastFilterSet


class WizardCustomFilterViewSet(ModelViewSet):
Expand All @@ -134,3 +135,9 @@ class WizardCustomFilterViewSet(ModelViewSet):
class ReservationViewSet(ModelViewSet):
queryset = models.Reservation.objects.all()
serializer_class = serializers.ReservationSerializer


class TrainingPitchViewSet(ModelViewSet):
queryset = models.TrainingPitch.objects.all()
serializer_class = serializers.TrainingPitchSerializer
filterset_class = filters.TrainingPitchFilterSet
Loading