off opps from those leads, and then some Deal.objects.filter(opportunity__lead__in=very_complex_leads_queryset) .filter(...) .order_by(...) Sad truth: There does come a point at which MySQL can't handle our the madness anymore.
# Need deals off opps from those leads, and then some Deal.objects.filter(opportunity__lead_id__in=very_complex_leads_queryset_ids) .filter(...) .order_by(...) Bad news: This ALSO sucks, because Django.
amounts of data from MySQL, and they're even worse at sending them back. Additionally, MySQL can't optimize a join against 100,000 random ids. What it CAN do is sh*t the bed.
keep it in MySQL and build a queryset to reference it temp_queryset = tempify_queryset(very_complex_leads_queryset) # Now doing a simple join against an indexed already-in-memory table (holla) Deal.objects.filter(opportunity__lead_id__in=temp_queryset) .filter(...) .order_by(...) • calculated IDs are stored in memory by MySQL, so no cost to transfer • temporary table is fully-indexed, making it very fast for joining • temp_queryset is a fully-fledged QuerySet - no functionality lost* • the whole process has negligible overhead.