sarath kumar sontam
sarath kumar sontam

Reputation: 45

RetrieveAPIView Django Rest framework, return custom response when lookup_field detail does not exists in database

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." }

Upvotes: 1

Views: 7226

Answers (1)

s6eskand
s6eskand

Reputation: 78

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

Upvotes: 3

Related Questions