https://www.hwaya2828.com/developers?userId=3064
# 예시 코드
class DeveloperViewSet(
mixins.RetrieveModelMixin,
viewsets.GenericViewSet,
):
...
filter_backends = (filters.DjangoFilterBackend,)
filterset_class = DeveloperFilter
...
# 예시 코드
class DeveloperFilter(CreatedFilterSet, django_filters.FilterSet):
for_user = django_filters.NumberFilter(
method='for_user_method',
help_text=f'Return developer for user',
)
...
class Meta:
model = Developer
fields = ()
...
def for_user_method(self, qs, name, value):
if value is None:
return qs.none()
try:
# 프론트에서 인코딩 되어 전달된 값을 user_id로 디코딩 과정
converted_id = value
...
user_id = origin_user_id
except:
raise Http404
qs = Developer.objects.filter(user_id=user_id, is_deleted=False)
...
return qs
Tip! Django: Default Lookup Field
class GenericAPIView(views.APIView): """ Base class for all other generic views. """ ... # If you want to use object lookups other than pk, set 'lookup_field'. # For more complex lookup requirements override `get_object()`. lookup_field = 'pk' lookup_url_kwarg = None ...
# 예시 코드
...
def get_object(self):
queryset = self.filter_queryset(self.get_queryset())
lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
assert lookup_url_kwarg in self.kwargs, (
'Expected view %s to be called with a URL keyword argument '
'named "%s". Fix your URL conf, or set the `.lookup_field` '
'attribute on the view correctly.' %
(self.__class__.__name__, lookup_url_kwarg)
)
try:
# 프론트에서 인코딩 되어 전달된 값을 user_id로 디코딩 과정
converted_id = self.kwargs[lookup_url_kwarg]
...
user_id = origin_user_id
except:
raise Http404
filter_kwargs = {self.lookup_field: user_id}
try:
obj = _get_object_or_404(queryset, **filter_kwargs)
except (TypeError, ValueError, ValidationError):
raise Http404
self.check_object_permissions(self.request, obj)
return obj