Joseph Adam
Joseph Adam

Reputation: 1652

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:

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)

Upvotes: 1

Views: 808

Answers (2)

Jake Somerville
Jake Somerville

Reputation: 76

Is an old post but for those landing here in future, there is no need to manually do the get. DRF retrieve method will lookup the object based on the lookup_field attribute. By default this is set to 'pk' but you can set this to whatever you want on your view. For this example it would be:

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

View as

class SingleUploadItem(RetrieveAPIView):
    queryset = fileUpload.objects.all()
    serializer_class = fileUploadSerializer
    lookup_field = 'file_name'

Upvotes: 0

Metalgear
Metalgear

Reputation: 3457

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)

Upvotes: 3

Related Questions