[Answered ]-Badly affecting performance in populating ManyToMany field values in rest api (using django rest framework)

2๐Ÿ‘

I always use django-debug-toolbar to debug my queryset to find bottleneck/duplicate query in my project. Django orm always using lazy load to retrieve related fields from database.
You can change this default behavior of your queryset by eager load your many to many field using prefetch_related.

class ProductViewSet(viewsets.ModelViewSet):
    queryset = Product.objects.prefetch_related('tag').all()
    serializer_class = ProductSerializer

Reference: prefetch_related

๐Ÿ‘คAdiyat Mubarak

Leave a comment