Hello to everyone,
i have a viewset (ModelViewset) for a model in my views.py, and i would like the list endpoint to list me things matching some parameters (but the are optional). So i have built this mixin:
class MultipleFieldLookupMixin(object):
"""
Apply this mixin to any view or viewset to get multiple field filtering
based on a `lookup_fields` attribute, instead of the default single field filtering.
"""
def get_object(self):
queryset = self.get_queryset() # Get the base queryset
queryset = self.filter_queryset(queryset) # Apply any filter backends
filter = {}
for field in self.lookup_fields:
if self.kwargs[field] is not None: # Ignore empty fields.
filter[field] = self.kwargs[field]
obj = get_object_or_404(queryset, **filter) # Lookup the object
return obj
class UserView(MultipleFieldLookupMixin, viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
lookup_fields = ['username', 'pwd', 'token_confirm', 'email', 'token_cng_pwd']
This is what my view.py looks like.
However the list view doesn't filter object at all, so i am missing something important.
Can anyone help me out or point me in the right direction?
Thanks a lot
Agnese Camellini