1

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)
3
  • What is the name of the fileupload serializer class? Commented May 22, 2022 at 18:22
  • FileUploadSerializer @David Lu Commented May 22, 2022 at 18:22
  • fileUploadSerializer or FileUploadSerializer ? Commented May 22, 2022 at 18:25

2 Answers 2

3

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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'

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.