[Answered ]-Iterating manyToOne relationship in django executes hundreds of queries

2đź‘Ť

âś…

Try using select-related. I am copying from the docs:

Returns a QuerySet that will “follow” foreign-key relationships, selecting additional related-object data when it executes its query. This is a performance booster which results in a single more complex query but means later use of foreign-key relationships won’t require database queries.

So your queryset should be something like this:

queryset = Users.objects.select_related('business ').annotate(num_assets=Count('assets',
      distinct=True),
      num_tickets=Count('tickets'),
 )
👤Serafeim

Leave a comment