I thought of trying to use select_realted in Django view to boost the performance. And I compare the results before using select_realted and after using it.
Although I see the reduction of significant number of queries, the time however rises. So I am not sure whether to use select_related in every view or not use them.
I just want to know when to use them and when not to.
My view is :
Before:
class ProductAPIView(ListAPIView):
permission_classes = [AllowAny]
serializer_class = ProductSerializer
queryset = Product.objects.all()
After:
class ProductAPIView(ListAPIView):
permission_classes = [AllowAny]
serializer_class = ProductSerializer
#queryset = Product.objects.all()
queryset = Product.objects.select_related('merchant','brand','collection','sub_category')
pagination_class = CustomPagination
My models:
class Product(models.Model):
merchant = models.ForeignKey(Seller,on_delete=models.CASCADE,blank=True,null=True)
category = models.ManyToManyField(Category, blank=False)
sub_category = models.ForeignKey(Subcategory, on_delete=models.CASCADE,blank=True,null=True)
brand = models.ForeignKey(Brand, on_delete=models.CASCADE)
collection = models.ForeignKey(Collection, on_delete=models.CASCADE)
featured = models.BooleanField(default=False) # is product featured?
The images before and after the use of select_related.
After:
Here we can see that the number of queries are reduced to 124, but the time is increased to 227. So, should i be using select_related? When to use it or when not to use it??