Friday, 26 November 2021

Django- Duplicated queries in nested models querying with ManyToManyField

How do I get rid of the duplicated queries as in the screenshot?

enter image description here


I have two models as following,

class Genre(MPTTModel):
    name = models.CharField(max_length=50, unique=True)
    parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, 
                             blank=True, related_name='children')

    def __str__(self):
        return self.name


class Game(models.Model):
    name = models.CharField(max_length=50)
    genre = models.ManyToManyField(Genre, blank=True, related_name='games')

    def __str__(self):
        return self.name

and have a serializer and views,

class GameSerializer(serializers.ModelSerializer):

    class Meta:
        model = Game
        exclude = ['genre', ]


class GenreGameSerializer(serializers.ModelSerializer):
    children = RecursiveField(many=True)
    games = GameSerializer(many=True,)

    class Meta:
        model = Genre
        fields = ['id', 'name', 'children', 'games']


class GamesByGenreAPI(APIView):
    queryset = Genre.objects.root_nodes()
    serializer_class = GenreGameSerializer

    def get(self, request, *args, **kwargs):
        ser = GenreGameSerializer(data=Genre.objects.root_nodes()
                                      .prefetch_related('children__children', 'games'), many=True)
        if ser.is_valid():
            pass
        return Response(ser.data)

so basically the model populated when serialized looks like this enter image description here

The result is what I am expecting but there are n duplicated queries for each of the genre. How can I fix it? Thanks..

here is a paste https://pastebin.com/xfRdBaF4 with all code, if you want to reproduce the issue.
Also add path('games/', GamesByGenreAPI.as_view()), in urls.py which is omitted in paste.

Update

tried logging queries to check if its issue with debug toolbar, but it is NOT, the queries are duplicated.. here is the screenshot. enter image description here



from Django- Duplicated queries in nested models querying with ManyToManyField

No comments:

Post a Comment