检索保存的实例时,ORM是否调用init? [英] Does the ORM call init when retrieving a saved instance?

查看:54
本文介绍了检索保存的实例时,ORM是否调用init?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在进行迁移,将可为空的字段更改为不可为空。新的 __ init __ 例程通过进行一些自定义的健美操训练以提供合适的默认值来确保字段不会为空。

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?

阅读源文件我怀疑ORM是否恢复了已保存数据的腌汁,因此我需要更新所有旧记录。但是我需要另一双眼睛。

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.

在检索保存的实例时,ORM调用是否初始化?

Does the ORM call init when retrieving a saved instance?

推荐答案

在django创建模型实例时,是否在模型上调用 __ init __ ?简短的答案是肯定的。如果使用get或切片查询集或对其进行遍历,则将调用 __ init __

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

但是覆盖 __ init __ 是'推荐的控制模型加载行为的方法。应该使用 from_db

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


从数据库加载时,from_db()方法可用于自定义模型实例的创建

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

db参数包含加载模型
的数据库的数据库别名,field_names包含所有已加载字段的名称,
,values包含

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.

这篇关于检索保存的实例时,ORM是否调用init?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆