Closed pyarun closed 3 years ago
You shouldn't pass the data you want to deserialize as keyword arguments to the serializer, but as the data
parameter.
The error you get seems to be because TypedJsonMixin
does type validation on the values of a dataclass instance, and that conflicts with our handling of non-supplied values. I'd suggest to ditch the TypedJsonMixin
, since the serializer does validation already.
You shouldn't pass the data you want to deserialize as keyword arguments to the serializer, but as the
data
parameter.
Changed the example code according to feedback. It was a mistake while writing code sample here. Sorry about it!
I went on to remove TypedJsonMixin
, and this error is resolved. But TypedJsonMixin
is giving 2 useful methods to_json
and to_dict
which are used in many places!
After serializer validation, we are getting OrderItem
instance in def create(self, validated_data)
method, which is awesome.
But after all processing when i have to save this data in django.contrib.postgres.fields.jsonb.JSONField
i need to convert OrderItem
instance to a dict
where to_dict
is very useful.
Still I replaced TypedJsonMixin
with https://pypi.org/project/dataclasses-json/
which is a subset of TypedJson and do not deal with type conversion and validation.
order_item.to_json() # order_item is OrderItem instance
We still have problem as OrderItem.description
has value of rest_framework.fields.empty
which cannot be converted to JSON and fails with
TypeError: Object of type type is not JSON serializable
I went on to remove
TypedJsonMixin
, and this error is resolved. ButTypedJsonMixin
is giving 2 useful methodsto_json
andto_dict
which are used in many places!
FYI Python has a native method to convert dataclasses to dicts: https://docs.python.org/3/library/dataclasses.html#dataclasses.asdict.
We still have problem as
OrderItem.description
has value ofrest_framework.fields.empty
which cannot be converted to JSON and fails withTypeError: Object of type type is not JSON serializable
You can call _strip_empty_sentinels()
to get rid of those empty values. However, as that method is still internal (for now) and actually has a different signature in master than in v0.8, it's probably a better idea to do a super-call to the create()
or update()
methods:
def create(self, validated_data):
order_item = super(MyCustomSerializerName, self).create(validated_data)
order_item.to_json()
I don't think there's anything actionable remaining here, so I'll close this issue for now.
Probably I am not using dataclass properly as this looks like a simple issue, here is my code
Now while creating an instance of ItemSerializer, I am not passing
description
andmessage
.I am getting the following error, as
empty_values
isrest_framework.fields.empty
Error
I read some existing issues about optional fields, but do not see a solution.