1.Why two methods?
to_python()
: Converts any input (database value, form data, manual assignment) into your Python object. It's the "universal converter" for the field.from_db_value()
: Only converts values fresh from the database (e.g., after a SELECT
query). It never handles form data or manual assignments.to_python()
is called in all contexts (DB reads, form validation, direct assignment like obj.field = "xyz"
).
from_db_value()
is only called for DB reads (and only if defined—older Django versions relied solely on to_python()
for DB values).
2.Why does to_python()
check for Hand
instances?
If you do obj.hand = Hand(...)
in code, Django calls to_python()
on that Hand
instance. The check avoids re-parsing an already-correct object. However, from_db_value()
never gets a Hand
instance. Database values are always raw strings (e.g., "AKQJ..."). So it skips this check.