Django Rest Framework get_queryset called more than once

When the request is executed in my ListAPIView, the get_queryset () method is called several times. It was called 4 times until I removed the default django model permissions, but now it is still called twice. What else can cause a repeated call.

class PropertyPledgeList(generics.ListAPIView):

    serializer_class = PledgeListSerializer

    ordering_fields = ('amount_cents')

    def get_queryset(self):
        slug = self.kwargs['slug']
        return get_object_or_404(Property, slug=slug).pledges.all().prefetch_related("user")
+4
source share
1 answer

Duplicate queries are the result get_object_or_404().

If you want to extract the parent object from the arguments of the URL keyword, you can set it as an attribute in the submit method, which is called only once, and then access the object already received in get_queryset().

from rest_framework.exceptions import NotFound

class PropertyPledgeList(generics.ListAPIView):
    queryset = PropertyPledge.objects.all()
    serializer_class = PledgeListSerializer

    def dispatch(self, request, *args, **kwargs):
        try:
            self.property = Property.objects.get(id=kwargs['slug'])
        except Property.DoesNotExist:
            self.property = None
        return super().dispatch(request, *args, **kwargs)

    def get_queryset(self):
        if not self.property:
            raise NotFound
        return self.property.get_pledges()
0
source

Source: https://habr.com/ru/post/1651907/


All Articles