Skip to content

Commit e432465

Browse files
Use db aggregation of python sum for total time
1 parent b0b001e commit e432465

File tree

2 files changed

+16
-13
lines changed

2 files changed

+16
-13
lines changed

project/tests/test_models.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -69,16 +69,15 @@ def test_time_spent_on_sql_queries_if_has_no_related_SQLQueries(self):
6969

7070
self.assertEqual(self.obj.time_spent_on_sql_queries, 0)
7171

72-
# FIXME probably a bug
7372
def test_time_spent_on_sql_queries_if_has_related_SQLQueries_with_no_time_taken(self):
7473

7574
query = SQLQueryFactory()
7675
self.obj.queries.add(query)
7776

7877
self.assertEqual(query.time_taken, None)
7978

80-
with self.assertRaises(TypeError):
81-
self.obj.time_spent_on_sql_queries
79+
# No exception should be raised, and the result should be 0.0
80+
self.assertEqual(self.obj.time_spent_on_sql_queries, 0.0)
8281

8382
def test_time_spent_on_sql_queries_if_has_related_SQLQueries_and_time_taken(self):
8483

silk/models.py

+14-10
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
IntegerField,
1818
ManyToManyField,
1919
OneToOneField,
20+
Sum,
2021
TextField,
2122
)
2223
from django.utils import timezone
@@ -124,16 +125,13 @@ def profile_table(self):
124125

125126
@property
126127
def time_spent_on_sql_queries(self):
128+
""""
129+
Calculate the total time spent in milli seconds on SQL queries using Django aggregates.
127130
"""
128-
TODO: Perhaps there is a nicer way to do this with Django aggregates?
129-
My initial thought was to perform:
130-
SQLQuery.objects.filter.aggregate(Sum(F('end_time')) - Sum(F('start_time')))
131-
However this feature isnt available yet, however there has been talk
132-
for use of F objects within aggregates for four years
133-
here: https://code.djangoproject.com/ticket/14030. It looks
134-
like this will go in soon at which point this should be changed.
135-
"""
136-
return sum(x.time_taken for x in SQLQuery.objects.filter(request=self))
131+
result = SQLQuery.objects.filter(request=self).aggregate(
132+
total_time=Sum('time_taken', output_field=FloatField())
133+
)
134+
return result['total_time'] or 0.0
137135

138136
@property
139137
def headers(self):
@@ -376,4 +374,10 @@ def is_context_profile(self):
376374

377375
@property
378376
def time_spent_on_sql_queries(self):
379-
return sum(x.time_taken for x in self.queries.all())
377+
"""
378+
Calculate the total time spent in milliseconds on SQL queries using Django aggregates.
379+
"""
380+
result = self.queries.aggregate(
381+
total_time=Sum('time_taken', output_field=FloatField())
382+
)
383+
return result['total_time'] or 0.0

0 commit comments

Comments
 (0)