Does the ORM call init when retrieving a saved instance?

你说的曾经没有我的故事 提交于 2020-01-05 04:11:31

问题


I'm doing a migration changing a nullable field to be not-nullable. The new __init__ routine ensures that fields can't be null by doing some custom callisthenics to come up with a suitable default.

The question is whether it is essential to migrate the existing data to apply the new rules for a default, or will those rules be applied automagically whenever a legacy object is retrieved?

Reading the source I suspect the ORM restores a pickle of the saved data, thus I would need to update all the old records. But I need another set of eyes.

Does the ORM call init when retrieving a saved instance?


回答1:


Does __init__ get called on a model when django creates a model instance? The short answer is yes. If you use get or if you slice a queryset or iterate through it __init__ will be called.

MyModel.objects.get(pk=1)
MyModel.objects.all()[2]
for p in MyModel.objects.all():
   print p.pk

however overriding __init__ isn't the recommended way to control model loading behaviour. That ought to be done with from_db

The from_db() method can be used to customize model instance creation when loading from the database.

The db argument contains the database alias for the database the model is loaded from, field_names contains the names of all loaded fields, and values contains the loaded values for each field in field_names.



来源:https://stackoverflow.com/questions/37175724/does-the-orm-call-init-when-retrieving-a-saved-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!