Django rest框架ListApiView慢查询

Django rest framework ListApiView slow query

我的显示器 table 有 147 行。我没有对这个数据集做任何繁重的计算,我只需要从数据库中快速获取它。目前,加载时间为 3-4 秒。其他数据来得真快,为什么呢? ListApiView 运行速度慢吗?

@permission_classes([AllowAny])
class DisplaysList(generics.ListAPIView):
    queryset = Displays.objects.all()
    serializer_class = serializers.DisplaySerializer



class Displays(models.Model):
    name = models.CharField(max_length=45, blank=True, null=True)
    owner = models.CharField(max_length=45, blank=True, null=True)

class GeoLocation(models.Model):
    id = models.CharField(primary_key=True, max_length=32,
                          default=generate_uuid)
    display = models.ForeignKey(
        Displays, on_delete=models.CASCADE, blank=True, null=True)
    lat = models.DecimalField(max_digits = 30, decimal_places=20, blank=True, null=True)
    lon = models.DecimalField(max_digits = 30, decimal_places=20, blank=True, null=True)

我觉得问题来了,如何高效的定位?

class DisplaySerializer(serializers.ModelSerializer):
    
    geolocation = serializers.SerializerMethodField()
    
    def get_geolocation(self, obj):
        gl = GeoLocation.objects.filter(display = obj)
        gll = list(gl.values)
        return gll

    class Meta:
        model = Displays
        fields = "__all__"
        

使用嵌套序列化程序,这样您就不必return通过方法

嵌套数据
class GeoLocationSerializer(serializers.ModelSerializer):

    class Meta:
        model = GeoLocation
        fields = "__all__"


class DisplaySerializer(serializers.ModelSerializer):
    
    geolocation_set = GeoLocationSerializer(many=True)

    class Meta:
        model = Displays
        fields = ["name", "owner", "geolocation_set"]

然后在您的视图中,使用 prefetch_related 在单个查询中获取嵌套数据。这会将您的查询减少到只有两个

@permission_classes([AllowAny])
class DisplaysList(generics.ListAPIView):
    queryset = Displays.objects.all().prefetch_related("geolocation_set")
    serializer_class = serializers.DisplaySerializer