Related objects related to Django

How can I count related objects in Django (less than N requests, where N is the number of objects).

To clarify, let's say I have tables A and B. Each B is related to the accuracy of one A. The approach I tried:

A.objects.select_related().filter(attr=val) A[i].B_set.count() 

Of course, for each A [i] I want to know the number of objects B. Django makes one request.

So the question is, is there a way to optimize it?

+4
source share
3 answers

I have not tried how many requests are being executed, but the Django method should use annotate() . For instance:

 from django.db.models import Count q = A.objects.select_related('B').annotate(num_B=Count('B')) print A[0].num_B 
+10
source

I have to answer my question :) If object A is requested like this:

 A.objects.select_related().filter(atrr=val).annotate(n_b=models.Count('B')) 

This creates a very long request, but at least there is only one.

+4
source

Since the aggregation function of Django 2.0 Count() accepts the filter parameter , which allows you to apply additional restrictions on the set of queries of related objects. It works as follows:

 A.objects.select_related().annotate( total=models.Count('myrelated__pk', filter=Q(only_items='that-i-need')) ).all() 
0
source

All Articles