digest: Reduce queries using select_related().

We use the message a lot for the query modified
here, so I think it's worth taking the up-front
hit of getting bulkier objects to avoid O(N)
hops back to the database.
This commit is contained in:
Steve Howell 2018-11-11 17:29:58 +00:00 committed by Tim Abbott
parent 51aa313833
commit f961408782
2 changed files with 6 additions and 3 deletions

View File

@ -201,7 +201,8 @@ def handle_digest_email(user_profile_id: int, cutoff: float) -> None:
all_messages = UserMessage.objects.filter(
user_profile=user_profile,
message__pub_date__gt=cutoff_date).order_by("message__pub_date")
message__pub_date__gt=cutoff_date
).select_related('message').order_by("message__pub_date")
context = common_context(user_profile)

View File

@ -12,7 +12,8 @@ from zerver.lib.digest import gather_new_streams, handle_digest_email, enqueue_e
gather_new_users
from zerver.lib.test_classes import ZulipTestCase
from zerver.lib.test_helpers import queries_captured
from zerver.models import get_client, get_realm, Realm, Message, UserActivity, UserProfile
from zerver.models import get_client, get_realm, flush_per_request_caches, \
Realm, Message, UserActivity, UserProfile
class TestDigestEmailMessages(ZulipTestCase):
@ -116,10 +117,11 @@ class TestDigestEmailMessages(ZulipTestCase):
result = self.client_post("/json/messages", payload)
self.assert_json_success(result)
flush_per_request_caches()
with queries_captured() as queries:
handle_digest_email(othello.id, cutoff)
self.assertTrue(41 <= len(queries) <= 42)
self.assertTrue(34 <= len(queries) <= 35)
self.assertEqual(mock_send_future_email.call_count, 1)
kwargs = mock_send_future_email.call_args[1]