简体   繁体   English

在Rest API中填充ManyToMany字段值时严重影响性能(使用Django Rest框架)

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

As I'm using django rest framework for building my product api. 当我使用django rest框架构建我的产品api时。

Here is my model in models.py 这是我在models.py中的模型

class Tag(models.Model):
    tag = models.CharField(max_length=10, unique=True)

class Product(models.Model):
    product_name = models.CharField(max_length=100)
    tag = models.ManyToManyField(Tag, blank=True, default=None, related_name='product_tag')

serializers.py : serializers.py:

class TagSerializer(serializers.ModelSerializer):
    class Meta:
        model = Tag
        fields = '__all__'

class ProductSerializer(serializers.HyperlinkedModelSerializer):
    tag = TagSerializer(many=True, read_only=True)

    class Meta:
        model = Product
        fields = '__all__'

views.py : views.py:

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

I have given the url for ProductViewset, so when I hit the api it gives me the results as well but it takes too much time to load, it takes around 2 minutes to give me the response. 我已经给出了ProductViewset的url,所以当我点击api时,它也可以给我结果,但是加载时间太长,大约需要2分钟才能给我响应。

I'm having 2000 product objects in database which needs to be populated. 我在数据库中有2000个产品对象,需要填充。

When I exclude the 'tag' field in "ProductSerializer", response comes very fast with all 2000 records. 当我排除“ ProductSerializer”中的“标签”字段时,所有2000条记录的响应速度很快。

Please suggest where is the loophole, why its affecting performance so much especially when I add this ManyToMany field. 请提出漏洞在哪里,为什么它会如此严重地影响性能,尤其是当我添加此ManyToMany字段时。

I always use django-debug-toolbar to debug my queryset to find bottleneck/duplicate query in my project. 我总是使用django-debug-toolbar调试我的查询集,以在项目中查找瓶颈/重复查询。 Django orm always using lazy load to retrieve related fields from database. Django orm始终使用延迟加载从数据库中检索相关字段。 You can change this default behavior of your queryset by eager load your many to many field using prefetch_related . 您可以通过渴望使用prefetch_related加载多对多字段来更改查询集的默认行为。

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

Reference: prefetch_related 参考: prefetch_related

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM