本文介绍了在Rest API中填充ManyToMany字段值时严重影响性能(使用Django Rest框架)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用django rest框架构建产品api时。

As I'm using django rest framework for building my product api.

这是我在models.py中的模型。

Here is my model in 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:

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

我已经给出了ProductViewset的网址,所以当我点击api时,它也可以给我结果,但是加载时间太长,大约需要2分钟内给我答复。

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.

我在数据库中有2000个需要填充的产品对象。

I'm having 2000 product objects in database which needs to be populated.

当我排除 ProductSerializer中的标签字段,则对所有2000条记录的响应都非常快。

When I exclude the 'tag' field in "ProductSerializer", response comes very fast with all 2000 records.

请提出漏洞在哪里,为什么它会如此严重地影响性能,尤其是当我添加此ManyToMany字段时。

Please suggest where is the loophole, why its affecting performance so much especially when I add this ManyToMany field.

推荐答案

我总是使用

这篇关于在Rest API中填充ManyToMany字段值时严重影响性能(使用Django Rest框架)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 09:50