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
dbargument contains the database alias for the database the model is loaded from,field_namescontains the names of all loaded fields, andvaluescontains the loaded values for each field infield_names. Thefield_namesare in the same order as thevalues. If all of the model’s fields are present, thenvaluesare 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.DEFERREDto each of the missing fields.
I am completely lost when reading above.
- 1st perception: "when loading from the database": for me,
loadingmeans reading / retrieving data from database, which means themodel instancealready 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 instancecreation, which conflicts with my 1st perception.
Q: Can someone please share why, when and how we use from_db() in Django ?