Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Filtering from custom DRF actions #104

Open
realnot opened this issue Nov 1, 2020 · 1 comment
Open

Filtering from custom DRF actions #104

realnot opened this issue Nov 1, 2020 · 1 comment

Comments

@realnot
Copy link

realnot commented Nov 1, 2020

I have this ViewSet with relative filters

class CityViewSet(ChoiceMixin, ReadOnlyModelViewSet):
    """
    A simple ViewSet for viewing cities.
    """
    queryset = City.objects.all()
    serializer_class = CitySerializer
    filter_fields = ["id", "code", "name", "land_code", "population", "province", "zone"]

Now ChoiceMixin add an action choices that turn a model into choices

class ChoiceMixin:
    """
    Transform queryset into choices
    """
    @action(detail=False)
    def choices(self, request):
        choices = self.get_queryset().only('pk', 'name').values_list('pk', 'name')
        data = [dict(key=k, value=v) for k, v in choices]

        if self.pagination_class is None:
            return Response(data)

        qs = self.paginator.paginate_queryset(data, self.request, view=self)
        return self.get_paginated_response(qs)

This will allow me to call

http://localhost:8000/api/core/city/  # to return cities with all serialized fields
http://localhost:8000/api/core/city/choices/ # to return only key: value (pk, name) fields

How I can run filters from inside choices mixin before to return response?

@realnot
Copy link
Author

realnot commented Nov 1, 2020

I just have to call

self.filter_queryset() passing a queryset like `choices`.

I don't delete question cause could be helpful to other devs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant