Reducing request time for PartList API

- Initial query time = 5.91s
- Prefetch related part categories = 3.64s
This commit is contained in:
Oliver Walters 2019-05-20 08:13:22 +10:00
parent 73041a3fe6
commit 6766063c8b
2 changed files with 8 additions and 0 deletions

View File

@ -110,6 +110,9 @@ class PartList(generics.ListCreateAPIView):
except PartCategory.DoesNotExist:
pass
# Ensure that related models are pre-loaded to reduce DB trips
parts_list = self.get_serializer_class().setup_eager_loading(parts_list)
return parts_list
permission_classes = [

View File

@ -58,6 +58,11 @@ class PartSerializer(serializers.ModelSerializer):
image_url = serializers.CharField(source='get_image_url', read_only=True)
category_name = serializers.CharField(source='category_path', read_only=True)
@staticmethod
def setup_eager_loading(queryset):
queryset = queryset.prefetch_related('category')
return queryset
class Meta:
model = Part
partial = True