[Answered ]-Django, different result between `all()` method and `all().values()` method

1👍

This is one of the very many reasons not to use .values() in the first place: this will make a database query, and then transform the items in dictionaries, and thus losing all model logic attached to it. This thus means that .img will no longer return a FieldFile object, but a simple string, and thus show the path relative to the media root, not the entire URL as is normally done through the FieldFile.

Your MyModelView also does not work with the serializer at all: you simply made an implementation of get, and thus there is no logic that works with the serializer.

Likely the easiest way is just work with a ListAPIView [classy-drf]:

from rest_framework.generics import ListAPIView


class MyModelView(ListAPIView):
    serializer_class = MyModelSerializer
    queryset = models.MyModel.objects.all()

or you can patch the get_queryset method:

from rest_framework.generics import ListAPIView


class MyModelView(ListAPIView):
    serializer_class = MyModelSerializer
    queryset = models.MyModel.objects.all()

    def get_queryset(self, *args, **kwargs):
        data = MyModelSerializer(data=self.request.data)
        if data.is_valid():
            return super().get_queryset(*args, **kwargs).filter(data.data['name'])
        return models.MyModel.objects.none()

    def post(self, request):
        return self.get(request)

But normally you do not use POST requests to retrieve data, but to create, update or delete data. Usually one uses a query string to filter the queryset.

Leave a comment