Easy way to exclude django _state attribute from jsonpickle.encode

528 Views Asked by At

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.

1

There are 1 best solutions below

0
On BEST ANSWER

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)