我有models.py
class Category(MPTTModel):
# few fields
class Brand(models.Model):
# few fields
class Attribute(models.Model):
# few fields
class AttributeValue(models.Model):
attributes = models.ForeignKey(Attribute, # other conditions)
# few fields
class Product(models.Model):
category = models.ForeignKey(Category, # other conditions)
brand = models.ForeignKey(Brand, # other conditions)
attributes = models.ManyToManyField(Attribute, # other conditions)
# few other fields
class ProductImages(models.Model):
product = models.ForeignKey(Product, # other conditions)
在views.py
中,我有
class ProductAPIView(generics.GenericAPIView):
serializer_class = ProductSerializer
queryset = Product.objects.all()
serializers.py
class ProductSerializer(serializers.ModelSerializer):
brand = serializers.SlugRelatedField(queryset = Brand.objects.all())
category = serializers.SlugRelatedField(queryset = Category.objects.all())
attributes = AttributeSerializer(many = True, read_only = True)
product_images = ProductImageSerializer(many = True, read_only = True)
我得到的JSON响应是这样的
{
"brand": ...,
"category": ...,
"attributes": [
{ "attribute_values": [...] },
{ "attribute_values": [...] }
],
"product_images": [{...}, {...}]
}
我遇到了select_related
和prefetch_related
,它们将优化外键字段和多对多字段的数据库查询。
我将查询集更改为queryset = Product.objects.select_related('category', 'brand').all()
如何更改ProductAPIView中的查询集,使其同时包含attributes
、product_images
和attribute_values
字段,并提高性能?
2条答案
按热度按时间u91tlkcl1#
您可以链接
select_realted
和prefetch_related
或覆盖
get_queryset
函数你可以使用Prefetch类来指定在prefetch_related()中使用的查询集,并以这种方式将其与select_related()组合:
hlswsv352#
对于你的问题的第一部分,你可以看看预取和这个问题。
为了调试的目的,我总是使用这个装饰器:
然后像这样使用它: