Try change this, If self.kwargs[field] is not None: With if self.kwargs[field]: <--- this will return True it the field is not empty This is the better way to filter, if you want filter the fields is empty then just add not like this example if not self.kwargs[field]:
On Sun, Jun 7, 2020, 1:06 AM Agnese Camellini <agnese.camell...@gmail.com> wrote: > 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 > > -- > You received this message because you are subscribed to the Google Groups > "Django users" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to django-users+unsubscr...@googlegroups.com. > To view this discussion on the web visit > https://groups.google.com/d/msgid/django-users/CACXuh-Siku2%2BES0RxCDfWe3NVRTnt3%3DBToj2ZFYB%2BbT1sBVCBg%40mail.gmail.com > <https://groups.google.com/d/msgid/django-users/CACXuh-Siku2%2BES0RxCDfWe3NVRTnt3%3DBToj2ZFYB%2BbT1sBVCBg%40mail.gmail.com?utm_medium=email&utm_source=footer> > . > -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAJepfJX0G%3DNxgoiBm3r2K5gv54Mz%3DAeSXoXf2a5UokjzkMVazg%40mail.gmail.com.