How to initialize Django model fields whose loading was deferred?

Viewed 404

I can overload the Model's __init__ to change the initialization behavior. But how to do the same when some of the model field loading are deferred? How do I run the initialization logic, which depends on the field values, when that fields are loaded later? Is there something similar to def clean_fieldname(self) that is called when the field is loaded later?

1 Answers

I found one can override Model.refresh_from_db() to hook into fields lazy loading. At the model class creation time, each field replace themselves with a data descriptor, that descriptors' __get__() does the lazy loading when the field is not present in the model instance's __dict__, it will call Model.refresh_from_db(fields=[fieldname]) where fieldname is the field that is being acessed.

Related