Changes between Initial Version and Version 1 of Ticket #30844


Ignore:
Timestamp:
Oct 6, 2019, 7:30:44 PM (5 years ago)
Author:
Robert Singer
Comment:

Legend:

Unmodified
Added
Removed
Modified
  • Ticket #30844 – Description

    initial v1  
    11I'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.
    22
    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`.
     3Overriding 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`.
    44
    5 Causes n+1 issue when iterating a QuerySet:
     5
     6== Current Problem
     7This will cause an n+1 issue when iterating a QuerySet:
    68{{{
    79class CatMixin(object):
     
    2527}}}
    2628
    27 The fix: Add a call to `obj.post_db_init()` to this line:
     29== The Fix
     30Add a call to `obj.post_db_init()` to this line:
    2831https://github.com/django/django/blob/master/django/db/models/query.py#L91
    2932
Back to Top