I was reading Django Official Doc for Model, it reads:
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, andvalues
contains the loaded values for each field infield_names
. Thefield_names
are in the same order as thevalues
. If all of the model’s fields are present, thenvalues
are guaranteed to be in the order__init__()
expects them. That is, the instance can be created bycls(*values)
. If any fields are deferred, they won’t appear infield_names
. In that case, assign a value ofdjango.db.models.DEFERRED
to each of the missing fields.
I am completely lost when reading above.
loading
means reading / retrieving data from database, which means the model instance
already exists or is created and stored in DB.from_db()
is for model instance
creation, which conflicts with my 1st perception.Q: Can someone please share why, when and how we use from_db()
in Django ?
After making a database query, Django will create model objects. It does this by calling the .from_db(…)
method [Django-doc]. If the query thus returns two records with as first record {'id': 14, 'name': 'foo'}
, and as second record {'id': 25, 'name': 'bar'}
, it will call the .from_db(…)
method twice with SomeModel.from_db('db-alias', ['id', 'name'], [14, 'foo'])
, and SomeModel.from_db('db-alias', ['id', 'name'], [25, 'bar'])
. This method is thus used to convert database data in model objects.
If you thus wish to customize how to convert data retrieved from the database, you can override the method, and for example pre-process the data in the parameters, or post-process the instance that is constructed. But I would be careful with this: there are, as with most of these methods, a few corner-cases, and if the adaptated method somehow fails to work on these, all sorts of logic might start to fail.