TypeError: Python object is not JSON serializable

前端 未结 3 937
慢半拍i
慢半拍i 2021-01-04 23:58

I am trying to encode an object into json using json.dumps() in Django, however when I pass in a python object, it raises this error.

TypeError         


        
3条回答
  •  花落未央
    2021-01-05 00:24

    The __dict__ gives all the attributes of the instance, but you don't want all that extra baggage - for the purposes of serialization, you are only interested in the fields.

    Your model does not contain anything special so the built-in helper function model_to_dict should be enough for your needs:

    import json
    from django.forms.models import model_to_dict
    
    oi = OrgInvite.objects.get(token=100) 
    oi_dict = model_to_dict(oi)
    oi_serialized = json.dumps(oi_dict)
    

    Your example was simple, only containing CharField, BooleanField, and ForeignKey all of which we can dump to json trivially.

    For more complicated models, you might consider writing your own serializer. In this case, I recommend using the popular django-rest-framework which does all the work for you.

    from rest_framework import serializers
    
    class OrgInviteSerializer(serializers.ModelSerializer):
        class Meta:
            model = OrgInvite
            fields = '__all__'
    

提交回复
热议问题