problem filtering queryset in Django Rest Framework

92 views
Skip to first unread message

Agnese Camellini

unread,
Jun 6, 2020, 2:06:54 PM6/6/20
to django...@googlegroups.com
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

wongX Ndeso

unread,
Jun 7, 2020, 6:34:01 AM6/7/20
to django...@googlegroups.com
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]:

--
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...@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.
Reply all
Reply to author
Forward
0 new messages