[Django]-How to fix "Potential unnecessary eager load detected on `LogEntry.user`"

3đź‘Ť

I found N+1 to rarely be happy with Django admin – either related entries (like user groups) are loaded lazily and it makes a N+1 problem in big listings, or they are prefetched() and then it’s on single-user pages that an “unnecessary eager load” is detected.

The problem is that the same base ModelAdmin querysets are used for listing pages and for single-object pages, so avoiding both problems is not easy.

Until someone comes with an easy solution to create different “prefetch” querysets for different admin pages, I’ve whitelisted these models like so. Just check with the django debug toolbar that no N+1 requests happen on these admin pages.

NPLUSONE_WHITELIST = [
    {"model": "admin.LogEntry", "field": "user"},
    {"model": "accounts.User", "field": "groups"},
]

Leave a comment