Skip to content

optimize sql#683

Open
mitchelljkotler wants to merge 1 commit into
allanlasser/issue666from
mitch/issue666
Open

optimize sql#683
mitchelljkotler wants to merge 1 commit into
allanlasser/issue666from
mitch/issue666

Conversation

@mitchelljkotler
Copy link
Copy Markdown
Member

querysets.py

  • Replaced EntitlementGrantQuerySet.matching() (Python loop + matches() call + N hidden queries) with for_org() — a pure SQL method that expresses all matching logic as Q objects using the org's known scalar attributes.
  • Rewrote EntitlementQuerySet.for_organization() to pass the lazy for_org() queryset directly as a subquery instead of materializing grant PKs with [g.pk for g in ...].

serializers.py

  • Added from django.db.models import Q.
  • Rewrote get_entitlements() to compute matching_grants = EntitlementGrant.objects.for_org(obj) once, use it in the Entitlement.objects.filter(...) query, and iterate it again (with prefetch_related("entitlements")) for the grant_update_on map — eliminating the second
    call to matching().

tasks.py

  • Replaced the for grant in ... N+1 loop in restore_organization() with collecting querysets per grant and merging them via .union(), so all matching-org lookups go through one SQL UNION query instead of N separate queries.

@allanlasser allanlasser temporarily deployed to squarelet-pi-mitch-issu-dvqe6o May 21, 2026 18:01 Inactive
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants