API endpoint for django `Group` model generating excess number of queries
Asked Answered
T

0

0

I am trying to build an endpoint for the default django's Group model, which has name and permissions fields:- Here are my view and serializers:-

Serializers.py:-

class GroupSerializer(serializers.ModelSerializer):

    class Meta:
        model = Group
        fields = ('id', 'name', 'permissions')

    def create(self, validated_data):
        permissions = validated_data.pop('permissions')
        instance = self.instance or self.Meta.model(**validated_data)
        instance.full_clean()
        instance.save()
        instance.permissions.add(*permissions)
        return instance

    def update(self, instance, validated_data):
        if 'permissions' in validated_data:
            permissions = validated_data.pop('permissions')
            instance.permissions.clear()
            instance.permissions.add(*permissions)
        instance.full_clean()
        return super().update(instance, validated_data)

Views.py:-

class GroupListCreateView(ListCreateAPIView):
    queryset = Group.objects.all()
    serializer_class = GroupSerializer


class GroupDetailView(RetrieveUpdateDestroyAPIView):
    queryset = Group.objects.order_by('name')
    serializer_class = GroupSerializer

with this serializers, and views I am facing a issue which is known as N+1 issue, that is the number of queries is really shooting high:-

enter image description here

enter image description here

enter image description here

Can I please get any help on this.

Group & Permission model is the default model which comes with django(copy pasting it):-

class Group(models.Model):
    objects: GroupManager

    name = models.CharField(max_length=150)
    permissions = models.ManyToManyField(Permission)

class Permission(models.Model):
    content_type_id: int
    objects: PermissionManager

    name = models.CharField(max_length=255)
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    codename = models.CharField(max_length=100)

Referencing the model in the docs:- https://docs.djangoproject.com/en/3.2/ref/contrib/auth/#permission-model

Thrive answered 6/8, 2021 at 13:33 Comment(2)
Can you share your related models (so Group and Permission I guess)?Harbinger
Updated the question, have a lookThrive

© 2022 - 2024 — McMap. All rights reserved.