Skip to content

Commit

Permalink
Merge pull request #5592 from nyaruka/ticket_queries
Browse files Browse the repository at this point in the history
Fix N+1 queries on ticket fetches
  • Loading branch information
rowanseymour authored Oct 29, 2024
2 parents fa6a53d + 46ec65e commit 3e5c42c
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 4 deletions.
7 changes: 6 additions & 1 deletion temba/tickets/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -603,6 +603,9 @@ def test_list(self):
# we have a specific ticket so we should show context menu for it
self.assertContentMenu(deep_link, self.admin, ["Edit", "Add Note", "Start Flow"])

with self.assertNumQueries(11):
self.client.get(deep_link)

# try to link to our ticket but with mismatched status
deep_link = f"{list_url}all/closed/{str(ticket.uuid)}/"

Expand Down Expand Up @@ -740,7 +743,9 @@ def assert_tickets(resp, tickets: list):
self.create_outgoing_msg(contact3, "Yes", created_by=self.agent)

# fetching open folder returns all open tickets
response = self.client.get(open_url)
with self.assertNumQueries(12):
response = self.client.get(open_url)

assert_tickets(response, [c2_t1, c1_t2, c1_t1])

joes_open_tickets = contact1.tickets.filter(status="O").order_by("-opened_on")
Expand Down
6 changes: 3 additions & 3 deletions temba/tickets/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -422,7 +422,7 @@ def get_context_data(self, **kwargs):
last_msg_ids = Msg.objects.filter(contact_id__in=contact_ids).values("contact").annotate(last_msg=Max("id"))
last_msgs = Msg.objects.filter(id__in=[m["last_msg"] for m in last_msg_ids]).select_related("created_by")

context["last_msgs"] = {m.contact: m for m in last_msgs}
context["last_msgs"] = {m.contact_id: m for m in last_msgs}
return context

def render_to_response(self, context, **response_kwargs):
Expand All @@ -446,10 +446,10 @@ def as_json(t):
"""
Converts a ticket to the contact-centric format expected by our frontend components
"""
last_msg = context["last_msgs"].get(t.contact)
last_msg = context["last_msgs"].get(t.contact_id)
return {
"uuid": str(t.contact.uuid),
"name": t.contact.get_display(),
"name": t.contact.get_display(org=self.request.org),
"last_seen_on": t.contact.last_seen_on,
"last_msg": msg_as_json(last_msg) if last_msg else None,
"ticket": {
Expand Down

0 comments on commit 3e5c42c

Please sign in to comment.