理解 Django 中的 Model.from_db()

Understanding Model.from_db() in Django

我正在阅读 Django Official Doc for Model,上面写着:

classmethod Model.from_db(db, field_names, values)¶

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. The field_names are in the same order as the values. If all of the model’s fields are present, then values are guaranteed to be in the order __init__() expects them. That is, the instance can be created by cls(*values). If any fields are deferred, they won’t appear in field_names. In that case, assign a value of django.db.models.DEFERRED to each of the missing fields.

看完上面我完全迷路了

问:有人可以分享我们为什么、何时以及如何在 Django 中使用 from_db() 吗?

模型数据在数据库中以行的形式存在,当通过查询从数据库中检索此数据时,必须将原始数据转换为模型实例,Model.from_db 是执行此转换的方法。

1st perception: "when loading from the database": for me, loading means reading / retrieving data from database, which means the model instance already exists or is created and stored in DB.

这几乎是正确的,模型数据存在于数据库中,模型实例是在查询该数据时通过此方法创建的

2nd perception: "be used to customize model instance creation", as well as the 2nd paragraph all makes me feel that this from_db() is for model instance creation, which conflicts with my 1st perception.

这是正确的,Model.from_db 是实例创建,可以覆盖以自定义该过程

进行数据库查询后,Django 将创建模型对象。它通过调用 .from_db(…) method [Django-doc] 来实现。如果查询 returns 两条记录,第一条记录 {'id': 14, 'name': 'foo'},第二条记录 {'id': 25, 'name': 'bar'},它将调用 .from_db(…) 方法两次 SomeModel.from_db('db-alias', ['id', 'name'], [14, 'foo']),并且SomeModel.from_db('db-alias', ['id', 'name'], [25, 'bar'])。因此,该方法用于转换模型对象中的数据库数据。

如果您因此希望自定义如何转换从数据库中检索到的数据,您可以覆盖该方法,例如预处理参数中的数据,或者post-处理实例建造。