#30844: Add after_db_init() hook method to model
-------------------------------------+-------------------------------------
Reporter: rsinger86 | Owner: nobody
Type: New feature | Status: closed
Component: Database layer | Version: master
(models, ORM) |
Severity: Normal | Resolution: wontfix
Keywords: | Triage Stage:
| Unreviewed
Has patch: 0 | Needs documentation: 0
Needs tests: 0 | Patch needs improvement: 0
Easy pickings: 0 | UI/UX: 0
-------------------------------------+-------------------------------------
Comment (by rsinger86):
Replying to [comment:5 felixxm]:
> `select_related()` is not related with `Model`'s initialization it's a
`QuerySet` method, so I cannot imagine how you would like to connect them.
As you pointed out there are many ways to solve your issues in the current
Django (e.g. you can
[https://docs.djangoproject.com/en/2.2/topics/db/managers/#modifying-a-manager-s
-initial-queryset add select_related() to the initial QuerySet] and use
`@cached_property`, there is also
[https://docs.djangoproject.com/en/2.2/ref/signals/#post-init post_init]
signal). You can use one of
[https://code.djangoproject.com/wiki/TicketClosingReasons/UseSupportChannels
support channels] to describe your real use case and get help.
I appreciate the quick response to the ticket, but I feel I may have
failed to convey what the issue is. The problem is that a model's
initialization lifecycle currently lacks a way to hook into the moment
right after the ORM populates FK relations that are specified in
`select_related`. The point where that happens is right here:
https://github.com/django/django/blob/master/django/db/models/query.py#L91
The nearest point to this moment is `__init__`, but it occurs before FK
relations are populated, so examining FK related field values at that
point will cause an n+1 query problem. There is no workaround/support for
hooking into this moment currently: modifying an initial queryset or using
the @cached_property won't work. I am glad to submit a pull request to add
this feature. But it's probably something only advanced users/library
authors need, so it may be out of scope. My use case is enhancing my
library, [https://github.com/rsinger86/django-lifecycle django-lifecycle],
to more efficiently support state transitions based on FK values.
--
Ticket URL: <https://code.djangoproject.com/ticket/30844#comment:6>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
--
You received this message because you are subscribed to the Google Groups
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-updates/067.9a0708ecbeaee008f8d4bf09430d7623%40djangoproject.com.