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.
- 1st perception: "when loading from the database": for me,
loading
means reading / retrieving data from database, which means themodel 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 formodel instance
creation, which conflicts with my 1st perception.
Q: Can someone please share why, when and how we use from_db()
in Django ?
CodePudding user response:
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.
CodePudding user response:
Model data exists as rows in the DB, when this data is retrieved from the DB via queries the raw data has to be converted into model instances, Model.from_db
is the method that performs this conversion.
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.
This is almost correct, model data exists in the database, model instances are created by this method when that data is queried
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.
This is correct, Model.from_db
is for instance creation and can be overridden to customise that process