You haven’t posted your new models (with the indexes defined) or the new query, so it’s going to be tough for me to offer any specific suggestions. However, it’s pretty clear that you’ve still got a couple of sequential scans being performed:
[quote="valeriuv, post:7, topic:23707"]
Presorted Key: dispatchers_dispatcher.id
-> Nested Loop Left Join (cost=4.97..5879573.75 rows=7479 width=1009)
-> Nested Loop Left Join (cost=0.29..108.41 rows=22 width=945)
Join Filter: (dispatchers_dispatcher.company_id = dispatchers_company.id)
-> Nested Loop Left Join (cost=0.29..64.16 rows=22 width=189)
-> Index Scan using dispatchers_dispatcher_pkey on dispatchers_dispatcher (cost=0.14..12.47 rows=22 width=63)
-> Index Scan using dispatchers_location_pkey on dispatchers_location (cost=0.15..2.35 rows=1 width=126)
Index Cond: (id = dispatchers_dispatcher.location_id)
-> Materialize (cost=0.00..11.50 rows=100 width=756)
-> Seq Scan on dispatchers_company (cost=0.00..11.00 rows=100 width=756)
[/quote]
and
[quote="valeriuv, post:7, topic:23707"]
-> GroupAggregate (cost=0.00..785.95 rows=3 width=40)
Group Key: v0_1.dispatcher_id
-> Nested Loop (cost=0.00..2.57 rows=3 width=34)
-> Seq Scan on dispatchers_dispatcher v2_1 (cost=0.00..1.27 rows=1 width=21)
Filter: (id = dispatchers_dispatcher.id)
-> Seq Scan on dispatchers_bonuscustomer v0_1 (cost=0.00..1.26 rows=3 width=21)
Filter: (dispatcher_id = dispatchers_dispatcher.id)
[/quote]
which means there may be more indexes worth adding.
I also would not rule out the possibility that it may still be better to break this query down into smaller queries and perform the aggregation within your code.