Further query reduction

- Also improved query reporting middleware
This commit is contained in:
Oliver Walters 2019-05-20 23:26:27 +10:00
parent d15b09a5f4
commit 8adb4f6c20
2 changed files with 23 additions and 0 deletions

View File

@ -3,6 +3,7 @@ from django.urls import reverse_lazy
from django.db import connection from django.db import connection
import logging import logging
import time import time
import operator
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -55,9 +56,18 @@ class QueryCountMiddleware(object):
if len(connection.queries) > 0: if len(connection.queries) > 0:
queries = {}
for query in connection.queries: for query in connection.queries:
query_time = query.get('time') query_time = query.get('time')
sql = query.get('sql').split('.')[0]
if sql in queries:
queries[sql] += 1
else:
queries[sql] = 1
if query_time is None: if query_time is None:
# django-debug-toolbar monkeypatches the connection # django-debug-toolbar monkeypatches the connection
# cursor wrapper and adds extra information in each # cursor wrapper and adds extra information in each
@ -73,4 +83,7 @@ class QueryCountMiddleware(object):
a=total_time, a=total_time,
b=(t_stop - t_start))) b=(t_stop - t_start)))
for x in sorted(queries.items(), key=operator.itemgetter(1), reverse=True):
print(x[0], ':', x[1])
return response return response

View File

@ -34,6 +34,14 @@ class PartBriefSerializer(serializers.ModelSerializer):
url = serializers.CharField(source='get_absolute_url', read_only=True) url = serializers.CharField(source='get_absolute_url', read_only=True)
image_url = serializers.CharField(source='get_image_url', read_only=True) image_url = serializers.CharField(source='get_image_url', read_only=True)
@staticmethod
def setup_eager_loading(queryset):
queryset = queryset.prefetch_related('category')
queryset = queryset.prefetch_related('stock_items')
queryset = queryset.prefetch_related('bom_items')
queryset = queryset.prefetch_related('builds')
return queryset
class Meta: class Meta:
model = Part model = Part
@ -60,6 +68,8 @@ class PartSerializer(serializers.ModelSerializer):
def setup_eager_loading(queryset): def setup_eager_loading(queryset):
queryset = queryset.prefetch_related('category') queryset = queryset.prefetch_related('category')
queryset = queryset.prefetch_related('stock_items') queryset = queryset.prefetch_related('stock_items')
queryset = queryset.prefetch_related('bom_items')
queryset = queryset.prefetch_related('builds')
return queryset return queryset
class Meta: class Meta: