1

I am new to Django rest framework. I have a model and serializer. Trying to retrieve data using RetrieveAPIView using a lookup_field.

I want to return custom response when lookup_filed data does not exits in database.

Below is my view

class GetData(RetrieveAPIView):    
    serializer_class = DataSerializer
    lookup_field='id'
    action = "retrieve"
    def get_queryset(self):           
       Data.objects.all()   

This is my response: { "detail": "Not found." }

1
  • If you override def get_queryset(), please return the queryset, your code above does not return queryset, but return None. Commented Feb 26, 2021 at 6:14

1 Answer 1

3

As long as the object exists in the database, with the id you are querying on you should be able to retrieve the object using RetrieveAPIView as such:

in your views.py file:

class GetData(RetrieveAPIView):
    queryset = Data.objects.all()
    serializer_class = DataSerializer

in your urls.py file:

urlpatterns = [
    path('your_custom_path/<pk>', GetData.as_view())
]

This will return the object with the specified primary key (id) as defined in the path you run the request against.

GET /your_custom_path/2 will return the Data object with an id of 2. This super simple code is the benefit of using the RetrieveAPIView if you want to add more customizable filtering I would request looking into APIView on the official django rest framework docs

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.