GeeWee / django-auto-prefetching

Automatic prefetching for Django
MIT License
231 stars 18 forks source link

Overwriting `get_queryset` method #21

Closed milosh012 closed 4 years ago

milosh012 commented 4 years ago

Hi,

I have a problem using your mixin when my viewset is having their own custom get_queryset method. Its simple does not work... Short example:

class ArtistViewSet(AutoPrefetchViewSetMixin, viewsets.ModelViewSet):
  def get_queryset(self):
    return Artist.objects.filter(owner=self.request.user)

in this case, your mixin method get_queryset is not invoked at all...

Is there a way around to make this working? Thanks

GeeWee commented 4 years ago

You're right that the docs were wrong. This is the way to do it:

import django_auto_prefetching
from rest_framework.viewsets import ModelViewSet

class BaseModelViewSet(django_auto_prefetching.AutoPrefetchViewSetMixin, ModelViewSet):
    serializer_class = YourModelSerializer

    def get_queryset(self):
            # Simply do the extra select_related / prefetch_related here
            # and leave the mixin to do the rest of the work
            queryset = YourModel.objects.all()
            queryset = queryset.select_related('my_extra_field')
            return django_auto_prefetching.prefetch(queryset, self.serializer_class)