Home > database >  Convert model objects in OrderedDict to Json django
Convert model objects in OrderedDict to Json django

Time:10-22

In [32]: obj
OrderedDict([('code', 'COO21'),
             ('name', 'sai'),
             ('country', <Country: INDIA>)])

Error:-
TypeError: Object of type Country is not JSON serializable

Not able to convert model objects in ordered dict to json

CodePudding user response:

Override the to_representation() method in your serializer to customize the response when sending back to the view/controller. instance is the object of the serializing model.

    def to_representation(self, instance):
        ret = super().to_representation(instance)
        ret["country"] = instance.country.name if country else None
        return ret
  • Related