'serializer increases the query in django rest framwrork

I have an API that returns the data including ManyToMany relation's data as well, but when I see queries in Django Debug Toolbar so it's more than 100 queries at the backend which I think is not a good approach, even if the records increases so the queries also get increases. I just want fewer queries so the API can respond faster, is there any way to achieve it?

models.py

class Package(models.Model):
    name = models.CharField(max_length=255, default='')
    description = models.CharField(max_length=255, null=True, blank=True)
    project = models.ForeignKey(Project, on_delete=models.CASCADE, null=True)
    is_active = models.IntegerField(default=1, null=True)
    tags = models.ManyToManyField(Tag, related_name='packageroom')
    team_members = models.ManyToManyField(User,related_name='packages')
    account = models.ForeignKey(User, on_delete=models.CASCADE, null=True)

    class Meta:
        db_table = 'packages'

serializers.py

class TagSerializer(serializers.ModelSerializer):
    class Meta:
        model = Tag
        fields = '__all__'

class UserDetailSerializer(serializers.ModelSerializer):
    organization = OrganizationSerializer(read_only=True)
    organization_type = OrganizationTypeSerializer(read_only=True)
    role = RoleSerializer(read_only=True)
    image = serializers.ReadOnlyField()
    class Meta:
        model = User
        fields = ['id', 'first_name', 'last_name', 'username', 'organization', 'organization_type',
                  'role', 'email', 'image','image_url', 'contact_number', 'comet_uid']

class PackageSerializer(serializers.ModelSerializer):
    tags = TagSerializer(read_only=True, many=True) # added to fetch tags details
    team_members = UserDetailSerializer(read_only=True, many=True) # added to fetch team members details
    class Meta:
        model = Package
        fields = ['id', 'name', 'description', 'project', 'tags', 'team_members']

views.py

  query = Package.objects.filter(project=project_id, is_active=1).prefetch_related('tags', 'team_members').select_related('project', 'account')
  packages = PackageSerializer(query, many=True).data
  return Response(packages)

I just want fewer queries so the API can respond faster, is there any way to achieve it?

django toolbar screenshot

Query result without prefetch and select related:

enter image description here



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source