问题
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