You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
# Print SQLprint(Task.objects.filter(status='pending').query)
# Django Debug Toolbar (install in dev)# uv add --dev django-debug-toolbar# Query counting in testsfromdjango.test.utilsimportCaptureQueriesContextfromdjango.dbimportconnectionwithCaptureQueriesContext(connection) ascontext:
list(Task.objects.select_related('category').all())
print(f"Number of queries: {len(context)}")
forqueryincontext:
print(query['sql'])
Raw SQL
# Raw queryset (returns model instances)Task.objects.raw(''' SELECT * FROM tasks_task WHERE priority >= %s ORDER BY created_at DESC''', [3])
# Direct cursor (for complex queries)fromdjango.dbimportconnectionwithconnection.cursor() ascursor:
cursor.execute(''' SELECT category_id, COUNT(*) as count FROM tasks_task GROUP BY category_id ''')
results=cursor.fetchall()
📋 Submission Checklist
Optimized queries with select_related/prefetch_related