Vaibhav
Vaibhav

Reputation: 617

How to serialize a simple Dict using django-marshmallow?

I tried all the ways and when I validate the serializer by calling is_valid(), I always get an error.

class KVSFileMapSerializer(Schema):
    kv_map = fields.Dict()

kvs_result = {
    'trial': 'Config',
    'trial_1': 'Congig',
}

kvs_serializer = KVSFileMapSerializer(data=kvs_result)
kvs_serializer.is_valid()

The last line always returns 'False', I tried raising an exception and this is what I get,

{'trial': [ErrorDetail(string='Unknown field.', code='invalid')], 'trial_1': [ErrorDetail(string='Unknown field.', code='invalid')]}

This is the package that I use - django-marshmallow

Upvotes: 0

Views: 769

Answers (1)

Vishal Singh
Vishal Singh

Reputation: 6234

When you define a serializer with some fields you need to pass the same field to the serializer in order for the serializer to serialize the data.

kvs_result = {
    "trial": "Config",
    "trial_1": "Congig",
}

this data does not contain the serializer field key i.e kv_map so that why kvs_serializer.is_valid() will always return False.

Correct Data:

data = {"kv_map": {"trial": "Config", "trial_1": "Congig",}}

as you have defined the kv_map field as kv_map = fields.Dict() you need to pass a dictionary with its key as kv_map and its value a dictionary.

Upvotes: 1

Related Questions