Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django rest framework ListApiView slow query

I have a displays table with 147 rows. I am not doing any heavy computation on this data set I just need to get it fast from the database. For now, the load time is 3-4 seconds. Other data comes really fast, why? Does the ListApiView work slow?

@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)

I think the issue is here, how to get efficiently geolocation?

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__"
        

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use a nested serializer so that you don’t have to return the nested data via a method

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"]

Then in your view, use prefetch_related to get the nested data in a single query. This will reduce your queries to only two

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading