【发布时间】:2021-08-23 21:58:51
【问题描述】:
我想过尝试在 Django 视图中使用 select_realted 来提高性能。我比较了使用 select_realted 之前和之后的结果。
虽然我看到查询数量显着减少,但时间却在增加。所以我不确定是否在每个视图中都使用 select_related 或不使用它们。
我只想知道什么时候用,什么时候不用。
我的看法是:
之前:
class ProductAPIView(ListAPIView):
permission_classes = [AllowAny]
serializer_class = ProductSerializer
queryset = Product.objects.all()
之后:
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
我的模型:
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?
select_related 使用前后的图片。
之后:
这里我们可以看到查询次数减少到124,但时间增加到227。那么,我应该使用select_related吗?什么时候用什么时候不用??
【问题讨论】:
-
如果您不使用获取的关系,则使用
select_realted毫无意义。
标签: django api django-rest-framework django-views django-select-related