Home > Back-end >  string list as a parameter in url in django
string list as a parameter in url in django

Time:10-04

i am working in a search view which take two inputs as a filter :

  1. search word

2.cities (multi select)

i did it using serializer and it worked but paggination does not work because it was a post method , so i'm trying to take these inputs from url parameters , i tried this pattern :

    path(r"search/<str:search>/(?P<city>\w*)/",
            SearchView.as_view({"get": "search"}), name="search"),

but when i browse : http://127.0.0.1:8000/company/search/taxi/montrial/ it return Not Found: /company/search/ so how to pass the paramteres or is there another way to use paggination with post method

CodePudding user response:

I suggest to use pagination with get request or in case you should do it with post

class CustomPagination(pagination.PageNumberPagination):
def get_paginated_response(self, data):
    return Response({
        'links': {
            'next': self.get_next_link(), #you can read page number from url and put it here
            'previous': self.get_previous_link()
        },
        'count': self.page.paginator.count,
        'results': data
    }) 

to read data from url you can use request.query_params

https://www.django-rest-framework.org/api-guide/pagination/

CodePudding user response:

i solved it using the serializer method, inherit from viewsets.GenericViewsets which has pagingation methods

class SearchView(viewsets.GenericViewSet):
    permission_classes = [IsDriver]
    queryset = CompanyProfile.objects.all()
    serializer_class = SearchSerializer

    @action(methods=['get'], detail=False)
    def search(self, request, format=None):
        serializer = SearchSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        page = self.paginate_queryset(serializer.data["companies"])
        if page is not None:
            # used CompanyProfileSerializer to serialize the companies query
            serializer = CompanyProfileSerializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        return Response(serializer.data)
  • Related