Как получить данные на основе определенного поля в Django Rest Framework с помощью RetrieveAPIView?
С помощью приведенного ниже кода я могу получить данные на основе id
, как я могу обновить этот код, чтобы я мог получить данные на основе fileName вместо этого?
Мои урлы это
urlpatterns = [
path("items/<pk>", SingleUploadItem.as_view()),
]
Мои взгляды:
class SingleUploadItem(RetrieveAPIView):
queryset = fileUpload.objects.all()
serializer_class = fileUploadSerializer
Моя модель -
class fileUpload(models.Model):
fileName = models.CharField(max_length=200, unique=True, blank=True)
Сначала в urls.py
urlpatterns = [
path("items/<str:file_name>", SingleUploadItem.as_view()),
]
И в файле 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)
Надеюсь, это может помочь.