Re:Ban 1+N in Django
by btown on Sunday March 26, 2023 @06:33PM
(#35320393)
My Chaotic Good take on this: one could implement a qs.auto_fetch_deferred() that emits model instances with weak back-references to a WeakSet of all instances emitted, and on a deferred get on ANY instance, it prefetches that attribute onto ALL of the instances... so that it doesn't just complain, but actually fixes your 1+N issue. But here lies absolute madness...
[ Parent
| on HN ]
Re:Ban 1+N in Django
by readertime on Sunday March 26, 2023 @07:45PM
(#35320985)
I agree; Django (and many ORMs) have taken the opinion that if you load N instances of a model, and then you load a related field on 1 of them, you likely only want the 1 related field. If however they assumed that loading a related field implies you likely want all related fields, perhaps there’d be fewer instances of foot-gunning.
Actually there is such thing already https://pypi.org/project/django-auto-prefetch/
Not a monkey patch though, so will only work on the models you inherit from this.