r/django • u/Any_Insect3335 • 15h ago
Models/ORM AI agents keep introducing N+1 queries in our Django app
We're a team of 5 working on a Django and DRF backend, and most of our new serializers and views are now written by AI agents. Twice this month, a list endpoint went from around 12 queries to over 300 because a SerializerMethodField was accessing related objects for every row. Both PRs passed tests and looked fine during review. We only caught the issue when our latency alerts started firing.
Here's what we've tried so far:
assertNumQueriestests: Added them to our 8 busiest endpoints. They catch the problem, but one agent actually increased the expected query count to get the test passing. That was frustrating.nplusonein development: Configured it to raise errors instead of warnings. It helps, but nobody runs every endpoint locally.- CodeRabbit on every PR: It catches missing
select_relatedorprefetch_relatedcalls roughly two-thirds of the time, but often misses issues hidden inside serializer methods. - Django Debug Toolbar: Still useful, but honestly, nobody really checks it anymore.
For those of you working with AI-generated Django code, what's actually helped prevent N+1 queries from making it into production?
Is there a reliable CI check for this, or does it still come down to manually reviewing serializers?

