In order to develop custom Django model fields, I'm reading the documentation.
I have already developed my custom field (which is almost equal to that of the example, HandField
: a field mapped over a Python class... With the only difference that I inherit from models.CharField
and not models.Field
).
from external_library import ExternalClass
class ExternalClassField(models.CharField):
description = "An ExternalClass field"
def __init__(self, *args, **kwargs):
kwargs['max_length'] = 14
super(ExternalClassField, self).__init__(*args, **kwargs)
def from_db_value(self, value, expression, connection, context):
if value is None:
return value
return ExternalClass(value)
def to_python(self, value):
if isinstance(value, ExternalClass):
return value
if value is None:
return value
return ExternalClass(value)
def get_prep_value(self, value):
if value is None:
return value
if isinstance(value, ExternalClass):
return value.to_string()
return value
The field behave as expected. However, I'm stuck at this part of the documentation: the deconstruct() function.
In particular, what I don't understand is this:
- What exactly is the purpose of the deconstruct function?
- How come my field works perfectly well even without it (and even if I modify the
init
arguments)? - How and when is that Django calls the deconstruct function?
I don't want to blindly copy-paste code that I don't understand, but the documentation is not clear.