Ask Your Question
1

What is the process for printing the Django SQL query related to an aggregation?

asked 2022-11-10 11:00:00 +0000

lalupa gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-03-11 05:00:00 +0000

nofretete gravatar image

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()
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-11-10 11:00:00 +0000

Seen: 27 times

Last updated: Mar 11 '23