djangodjango-models

Understanding Model.from_db() in Django


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, 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.

I am completely lost when reading above.

Q: Can someone please share why, when and how we use from_db() in Django ?


Solution

  • 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.