Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To print the Django SQL query related to an aggregation, follow these steps:

  1. Import the connection module from django.db:
from django.db import connection
  1. Create a queryset with the aggregation function(s) and annotate the result:
from django.db.models import Count, Avg

qs = MyModel.objects.values('field1').annotate(num=Count('id'), avg=Avg('field2'))
  1. Use the query attribute of the queryset object to get the SQL query:
print(qs.query)
  1. Execute the queryset to get the result:
result = qs.all()