Django休息框架需要很长时间才能返回嵌套的序列化数据

时间:2015-09-05 06:13:13

标签: python django api rest django-rest-framework

我们有四个相关的模型,而返回查询集序列化数据太慢(serializer.data)。以下是我们的型号和序列化器。

为什么django嵌套的序列化程序花费太长时间才能返回渲染的响应。我们在这里做错了什么?

注意:从EC2实例连接时,我们的数据库位于AWS中,但是当从我的localhost尝试时,它非常慢。它返回的json大小为700KB。

models.py

class ServiceType(models.Model):
    service_name = models.CharField(max_length = 100)
    description = models.TextField()
    is_active = models.BooleanField(default = 1)

class Service(models.Model):
    service_name = models.CharField(max_length = 100)
    service_type = models.ForeignKey(ServiceType, related_name = "type_of_service")
    min_duration = models.IntegerField() ##duration in mins

class StudioProfile(models.Model):

   studio_group = models.ForeignKey(StudioGroup, related_name = "studio_of_group")
   name = models.CharField(max_length = 120)

class StudioServices(models.Model):
   studio_profile = models.ForeignKey(StudioProfile, related_name = "studio_detail_for_activity")
   service = models.ForeignKey(Service, related_name = "service_in_studio")

class StudioPicture(models.Model):
   studio_profile  = models.ForeignKey(StudioProfile, related_name = "pic_of_studio")
   picture = models.ImageField(upload_to = 'img_gallery', null = True, blank = True)

serializers.py

class ServiceTypeSerializer(serializers.ModelSerializer):

    class Meta:
       model = ServiceType
       fields = ('id', 'service_name')

class ServiceSerializer(serializers.ModelSerializer):

    service_type = ServiceTypeSerializer()
    class Meta:
        model = Service
        fields = ('id', 'service_type', 'service_name')

class StudioServicesSerializer(serializers.ModelSerializer):
    service = ServiceSerializer()
    class Meta:
        model = StudioServices
        fields = ('service','price','is_active','mins_takes')

class StudioPictureSerializer(serializers.ModelSerializer):
    class Meta:
        model = StudioPicture
        fields = ('picture',)

class StudioProfileSerializer(serializers.ModelSerializer):
    studio_detail_for_activity = StudioServicesSerializer(many = True)
    pic_of_studio = StudioPictureSerializer(many = True)
    class Meta:
       model = StudioProfile
       fields = ('id', 'name','studio_detail_for_activity','pic_of_studio')

views.py

class StudioProfileView(ListAPIView):
    serializer_class = StudioProfileSerializer
    model = StudioProfile
    def get_queryset(self):
        try:
           queryset = self.model.objects.all()
        except Exception ,e:
           logger_error.error(traceback.format_exc())
           return None
        else:
           return queryset

1 个答案:

答案 0 :(得分:2)

你检查过哪一部分是慢的吗?比如,你在那个数据库中有多少条记录?我会尝试运行查询并检查查询是否很慢,然后检查少于100个寄存器的序列化程序,等等。

我建议您阅读本文http://www.dabapps.com/blog/api-performance-profiling-django-rest-framework/,以评估如何分析您的API

此致