barseghyanartur / django-mongoengine-filter

django-filter for MongoEngine
https://pypi.org/project/django-mongoengine-filter/
13 stars 7 forks source link

Integrate with Django Rest Framework #13

Open leonardoarbache opened 2 years ago

leonardoarbache commented 2 years ago

There is a way to integrate it with the Django Rest classes ?

I've tried something like this but it just not working. The response always came empty and i can garatee that there's some documents to be returned.

class RelatorioViewSet(
    generics.ListCreateAPIView,
    FilterView
):
    filterset_class = RelatorioFilterSet
    serializer_class = RelatorioSerializer
    permission_classes = [AuthPermission]

    def get_queryset(self):
        return Relatorio.objects.all()

    def get(self, request, *args, **kwargs):
        filterset_class = self.get_filterset_class()
        self.filterset = self.get_filterset(filterset_class)
        page = self.paginate_queryset(self.filterset.qs)

        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(page, many=True)
        return Response(serializer.data)
oussjarrousse commented 1 year ago

You can use django-mongoengine-filter with Django Rest Framework Mongoengine which is based on DRF with support for MongoDB. You still need to pip install django-filters, and to INSTALLED_APPS.append('django_filters').

You have to define the RelatorioFilterSet class yourself...

import django_mongoengine_filter
class RelatorioFilterSet(django_mongoengine_filter.FilterSet):
   class Meta:
        model = RelatorioModel
        fields = [
            'name", # just an example of a string field that should be filterable
        ]
   name = django_mongoengine_filter.StringFilter()
barseghyanartur commented 1 year ago

Thanks for an excellent answer, @oussjarrousse. This is worth being mentioned in recipes if properly documented. Feel free to make a PR.

oussjarrousse commented 1 year ago

It would be my first experiment with docs. I will give it a try maybe over the weekend

leonardoarbache commented 1 year ago

That would be great @oussjarrousse. I kind forget this PR and forgot to update here haha I can confirm that this work i use it for years now image

image

I also would like to add that you can use methods and inside it the mongo pipelines. Its awesome :)