I have turned the User model from django.contrib.auth.models into an API using Django Rest Framework. When I perform a User.objects.all() query in the API, I end up with hundreds of queries like this, every time I call the API:
SELECT `django_content_type`.`id`,
`django_content_type`.`app_label`,
`django_content_type`.`model`
FROM `django_content_type`
WHERE `django_content_type`.`id` = 2
Hence the User API is quite slow.
Trying to optimise those out with prefetch_related I wound up with this query:
User.objects.all().prefetch_related('user_permissions__content_type__id')
But it produces the error:
'user_permissions__content_type__id' does not resolve to an item that supports
prefetching - this is an invalid parameter to prefetch_related().
So how do I reduce the query count down from hundreds to the five or six I can usually optimise django rest framework down to?
For the record, here is my full code (abridged for relevance):
from rest_framework import viewsets
from django.contrib.auth.models import User
class UserViewSet(viewsets.ModelViewSet):
model = User
filter_fields = ('username',)
def get_queryset(self):
if self.request.user.is_staff:
return User.objects.all().prefetch_related('user_permissions__content_type__id')
Note: this similar question is different because it's not referring to the built-in auth model. It's the built-in auth model that I am trying to use.