Changes between Initial Version and Version 1 of Ticket #30844
- Timestamp:
- Oct 6, 2019, 7:30:44 PM (5 years ago)
Legend:
- Unmodified
- Added
- Removed
- Modified
-
Ticket #30844 – Description
initial v1 1 1 I've encountered a need in my personal projects, and when writing [https://github.com/rsinger86/django-lifecycle django-lifecycle], to hook into the moment when a model has been fully initialized from the database. 2 2 3 Overriding the model's __init__ method does NOT work here because the `select_related` relationships have not yet been added in/cached in the model's FK fields. It would be useful to do things right after the model is fully loaded and initialized from the database. For example, if you have a "type" foreign key field, you may want to apply some polymorphic behavior based on the value of that field. Doing this in `__init__` will cause a n+1 query explosion if you do it when iterating over a`QuerySet`.3 Overriding the model's __init__ method does NOT work here because the `select_related` relationships have not yet been added in/cached in the model's FK fields. It would be useful to do things right after the model is fully loaded and initialized from the database. For example, if you have a "type" foreign key field, you may want to apply some polymorphic behavior based on the value of that field. Doing this in `__init__` will cause a n+1 query explosion if you load multiple models and iterate over the `QuerySet`. 4 4 5 Causes n+1 issue when iterating a QuerySet: 5 6 == Current Problem 7 This will cause an n+1 issue when iterating a QuerySet: 6 8 {{{ 7 9 class CatMixin(object): … … 25 27 }}} 26 28 27 The fix: Add a call to `obj.post_db_init()` to this line: 29 == The Fix 30 Add a call to `obj.post_db_init()` to this line: 28 31 https://github.com/django/django/blob/master/django/db/models/query.py#L91 29 32