Description
When Sentry captures exceptions in Django applications, it serializes local variables by calling repr() on them. This triggers Django's QuerySet.__repr__() which evaluates the query to display results, causing unexpected database queries during exception handling.
This is particularly problematic because:
- It adds latency to exception handling
- It can cause N+1 query issues in high-error scenarios
- The queries serve no purpose (results are just for display in Sentry UI)
- It can mask the original error if the query itself fails
Reproduction Steps
Minimal reproduction
from django.db import connection, reset_queries
from sentry_sdk.serializer import serialize
# Any Django model
from myapp.models import MyModel
reset_queries()
# Simulate what Sentry does during exception capture
qs = MyModel.objects.all()
serialize(qs)
print(f"Queries executed: {len(connection.queries)}")
# Output: Queries executed: 1
# Query: SELECT ... FROM myapp_mymodel LIMIT 21
Suggested Solutions
override django repr function for queryset objects