How can I bring user=pk in this case? I want to list on the basis of user's location

Viewed 46

I want to bring the user=pk in the 3rd line which is commented. I have no issue with changing the class to APIview from ListAPIview. How can I implement pk in this case? I tried writing a def get but was not able to call the customer.location.

class ServiceProviderList(generics.ListAPIView):
    # customer = CustomerProfile.objects.get(user=3)
    # queryset = ProfileCompletion.objects.filter(location__distance_lte=(customer.location,25))#all().order_by('-id')
    queryset = ProfileCompletion.objects.all()
    serializer_class=ProfilecompletioneSerializer
    filterset_class=SnippetFilter
    filter_backends = [DjangoFilterBackend,SearchFilter,OrderingFilter]
    filterset_fields = ['fullname', 'category','departments','services']
    search_fields = ['fullname', 'category__name','departments__dept_name','services__service_name']
    
2 Answers

You override the get_queryset method:

class ServiceProviderList(generics.ListAPIView):
    queryset = ProfileCompletion.objects.all()
    serializer_class=ProfilecompletioneSerializer
    filterset_class=SnippetFilter
    filter_backends = [DjangoFilterBackend,SearchFilter,OrderingFilter]
    filterset_fields = ['fullname', 'category','departments','services']
    search_fields = ['fullname', 'category__name','departments__dept_name','services__service_name']

    def get_queryset(self, *args, **kwargs):
        customer = CustomerProfile.objects.get(user=self.request.user)
        qs = super().get_queryset(*args, **kwargs):
        return qs.filter(
            location__distance_lte=(customer.location,25)
        ).order_by('-id')

@Surya, Good afternoon. One of the ways is to implement the Primary Key based operations. Many thanks.

class EmployeeDetailView(generics.RetrieveUpdateDestroyAPIView):
    queryset = Employee.objects.all()
    serializer_class = EmployeeSerializer
Related