JSON Serializing Django Models with simplejson

后端 未结 3 443
一整个雨季
一整个雨季 2020-12-07 10:21

I\'d like to use simplejson to serialize a Django model. Django\'s serializer doesn\'t support dictionaries... and simplejson doesn\'t support Django Querysets. This is quit

3条回答
  •  一生所求
    2020-12-07 10:44

    I would go with extending simplejson. Basically, you want to plug in django's serialization when the JSON encoder encounters a QuerySet. You could use something like:

    from json import dumps, loads, JSONEncoder
    
    from django.core.serializers import serialize
    from django.db.models.query import QuerySet
    from django.utils.functional import curry
    
    class DjangoJSONEncoder(JSONEncoder):
        def default(self, obj):
            if isinstance(obj, QuerySet):
                # `default` must return a python serializable
                # structure, the easiest way is to load the JSON
                # string produced by `serialize` and return it
                return loads(serialize('json', obj))
            return JSONEncoder.default(self,obj)
    
    # partial function, we can now use dumps(my_dict) instead
    # of dumps(my_dict, cls=DjangoJSONEncoder)
    dumps = curry(dumps, cls=DjangoJSONEncoder)
    

    For more info on default method, have a look at simplejson documentation. Put that in a python module, then import dumps and you're good to go. But note that this function will only help you serializing QuerySet instances, not Model instances directly.

提交回复
热议问题