I need to fetch a list of users and a list of permissions (guardian object permissions) each user has. The problem is that every way I am trying to do this runs into the N+1 problem. Whether I simply loop over the user list and get permissions from the set
for user in User.objects.all():
data = UserSerializer(user).data
data['permissions'] = PermissionSerializer(user.userobjectpermission_set, many=True)
Or if I use prefetch_related()
for user in User.objects.prefetch_related('userobjectpermission_set'):
data = UserAndPermSerializer(user).data
It ends up fetching the user list first and then running a separate permission query for every single user.
I can write a raw SQL statement and serialize it myself, but I would rather use the serializers I already have and so I would like to have the users and permissions as model instances. Any way to accomplish what I need using the ORM?
Django is version 1.11 LTS and I cannot upgrade to 2.x any time soon.