Skip to content

Commit

Permalink
update user filters
Browse files Browse the repository at this point in the history
  • Loading branch information
alperencubuk committed Aug 17, 2024
1 parent 6370402 commit 8cda8c7
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 9 deletions.
6 changes: 3 additions & 3 deletions apps/app/views/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,18 @@ class BaseModelViewSet(ModelViewSet):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.filterset_fields = {}
excluded_fields = {"image", "qr_code"}
filter_exclude = {"image", "qr_code"}

model_meta = self.get_queryset().model._meta

for field in model_meta.get_fields():
if field.name in excluded_fields:
if field.name in filter_exclude:
continue

if field.get_internal_type() == "ForeignKey":
related_model_meta = field.related_model._meta
for related_field in related_model_meta.get_fields():
if related_field.name not in excluded_fields:
if related_field.name not in filter_exclude:
self.filterset_fields[f"{field.name}__{related_field.name}"] = (
self.get_lookup(related_field.get_internal_type())
)
Expand Down
41 changes: 35 additions & 6 deletions apps/auth/views/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,18 @@ class UserViewSet(ModelViewSet):

def __init__(self, **kwargs):
super().__init__(**kwargs)
filter_exclude = ("password",)
self.filterset_fields = [
field.name
for field in self.get_queryset().model._meta.get_fields()
if field.name not in filter_exclude
]
self.filterset_fields = {}
filter_exclude = {"password"}

model_meta = self.get_queryset().model._meta

for field in model_meta.get_fields():
if field.name in filter_exclude:
continue

self.filterset_fields[field.name] = self.get_lookup(
field.get_internal_type()
)

@extend_schema(tags=["me"])
@action(detail=False, methods=["get", "patch", "delete"])
Expand Down Expand Up @@ -56,3 +62,26 @@ def destroy(self, request, *args, **kwargs):
user.is_active = False
user.save()
return Response(status=status.HTTP_204_NO_CONTENT)

@staticmethod
def get_lookup(field_type):
if field_type in ("CharField", "TextField"):
return [
"exact",
"iexact",
"contains",
"icontains",
"startswith",
"istartswith",
"endswith",
"iendswith",
]
if field_type in (
"IntegerField",
"FloatField",
"DecimalField",
"DateTimeField",
"BigAutoField",
):
return ["exact", "lt", "lte", "gt", "gte"]
return ["exact"]

0 comments on commit 8cda8c7

Please sign in to comment.