[Django]-Understanding Model.from_db() in Django

4👍

✅

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.

3👍

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

Leave a comment