Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to retrieve data based on specific field in Django Rest Framework using RetrieveAPIView?

With the code below, I am able to retrieve data based on id, how can I update this code so I can retrieve data based on fileName instead?

My urls is

urlpatterns = [
    path("items/<pk>", SingleUploadItem.as_view()),
]

My views is:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class SingleUploadItem(RetrieveAPIView):

    queryset = fileUpload.objects.all()
    serializer_class = fileUploadSerializer

My model is

class fileUpload(models.Model):
    fileName = models.CharField(max_length=200, unique=True, blank=True)

>Solution :

First, in urls.py

urlpatterns = [
    path("items/<str:file_name>", SingleUploadItem.as_view()),
]

And in views.py,

from rest_framework import status
from .models import fileUpload
from .serializers import FileUploadSerializer

class SingleUploadItem(RetrieveAPIView):

    queryset = fileUpload.objects.all()
    serializer_class = fileUploadSerializer

    def get(self, request, file_name):
        try:
            fileupload_obj = fileUpload.objects.get(fileName = file_name)
            return Response(FileUploadSerializer(fileupload_obj).data)
        except fileUpload.DoesNotExist:
            return Response(status = status.HTTP_400_BAD_REQUEST)

Hope it could help.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading