`assertNumQueries` is useful in *preventing* accidental N+1 in your views, 
and I sure which people would use a lot more.

But there are many situations where a N+1 can get created and people 
usually have don't write tests for (even if they should have). For example, 
assume this model:

```
# models.py

class Author(models.Model):
    name = models.CharField(max_length=100)


class Book(models.Model):
   title = models.CharField(max_length=100)
   author = models.ForeignKey(Author)


   class __str__(self):
      return f"{self.title}, by {self.author.name}"


# admin.py

admin.site.register(Book)
```

You shouldn't write a `__str__` that way in the first place, but in my 
experience I've seen way more `__str__` methods accessing related fields 
than tests checking `assertNumQueries` against admin views. Some additional 
logging would help me spot this issues before writing the tests.

The additional logging is not a solution, just a debugging tool to help fix 
the codebase by telling me where to add `select_related` _and_ prioritize 
what to write tests against.


On Tuesday, May 28, 2019 at 11:13:59 AM UTC-5, James Bennett wrote:
>
> Have you looked at the assertNumQueries assertion?
>
>
> https://docs.djangoproject.com/en/2.2/topics/testing/tools/#django.test.TransactionTestCase.assertNumQueries
>
> This can let you assert the expected queries and break your tests if 
> someone accidentally introduces an N+1.
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django developers  (Contributions to Django itself)" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-developers+unsubscr...@googlegroups.com.
To post to this group, send email to django-developers@googlegroups.com.
Visit this group at https://groups.google.com/group/django-developers.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-developers/147e8487-958c-4220-9114-d253ec653e20%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to