1π
β
I believe that a custom field may be of use in this instance.
class AgeField(serializers.WriteableField):
def to_native(self, age):
return age * 100
def from_native(self, age):
return int(age) / 100
class MySerializer(serializers.ModelSerializer):
age = AgeField(source='age')
def restore_object(self, attrs, instance=None):
"""
Deserialize a dictionary of attributes into an object instance.
You should override this method to control how deserialized objects
are instantiated.
"""
if instance is not None:
instance.update(attrs)
instance.update({'age', attrs['age'] / 100})
return instance
return attrs
class Meta:
model = MyModel
fields = ('field1', 'field2', 'age')
In this example, letβs say that the age is 10. In your serializer, you would display the following:
[
{
"field1": "value",
"field2": "value",
"age" : 100
},
]
The to_native
method will show the value as 100 as the form on the page. However, when submitting 100 as the value, the from_native
will trigger (with age
being unicode), and then be divided by 100, storing to the database as 10. Is this what you are looking for?
Or, if you are talking about strictly deserializing, the restore_object
code is likely what you are looking for in combination with to_native
.
π€Michael B
Source:stackexchange.com