Skip to content

Django QuerySet evaluation triggered during exception capture due to repr() on local variables #5414

@WaleedMeselhy

Description

@WaleedMeselhy

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:

  1. It adds latency to exception handling
  2. It can cause N+1 query issues in high-error scenarios
  3. The queries serve no purpose (results are just for display in Sentry UI)
  4. 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

Metadata

Metadata

Assignees

No one assigned

    Projects

    Status

    Waiting for: Product Owner

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions