简体   繁体   中英

Easy way to exclude django _state attribute from jsonpickle.encode

I have a python class which is not a Django model object:

class APIBase:
    data = object

    class Meta:
        abstract = True

    def toJSON(self):
        return jsonpickle.encode(self, unpicklable=False)

However the data attribute of this class can contain a Django model, and when this is encoded by jsonpickle, the JSON string contains a private _state attribute from Django, which I don't want encoded.

Is there an easy way to exclude this without resorting to writing my own encoder? I can rely on the fact that only the data attribute can contain the Django model.

I'm still learning python and django, but from my understanding the convention is any attribute starting with an underscore is considered private, so I was surprised to see this being encoded.

Figured it out:

def toJSON(self):
    clone = copy.deepcopy(self)
    if getattr(clone.data, '_state', False):
        del clone.data._state
    return jsonpickle.encode(clone, unpicklable=False)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM