Reputation: 1040
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??
Upvotes: 0
Views: 1052
Reputation: 2435
the select_related
in Django is actually JOIN
in SQL.
select_related
will fetch your related fields as well with your object in only one query.
for example imagine if you have a Book Model and you have this following code:
# Django will execute another query for getting author name
book = Book.objects.get(id=1)
author = book.author.name
# 2 queries executed
In this example you have executed only one query but for getting the author.name
Django will execute another query. But if you use select_related
Django will get the author too in just one query.
# Django won't execute another query for getting author name
book = Book.objects.select_related('author').get(id=1)
author = book.author.name
# 1 query executed
Note that you don't need to select all of your related objects in select_related
if you don't need them.
Please check out this link in stackoverflow to know what's the differences between select_related
and prefetch_related
and when to use them.
also check out this link to know more about n + 1 query problems.
Upvotes: 1