How to exclude specific fields on serialization with jsonpickle?

后端 未结 2 1715
失恋的感觉
失恋的感觉 2021-02-19 03:21

I\'m using SQLAlchemy extension with Flask. While serializing my models (which are also used for database operations) using jsonpickle, I want some specific attributes

2条回答
  •  清歌不尽
    2021-02-19 03:37

    This one will help others to get their task done:

    Make a class like this one in a package like your custom jsonpickle package:

    class SetGetState:
        def __getstate__(self):
            state = self.__dict__.copy()
            try:
                class_name = '_' + self.__class__.__name__ + '__'
                new_items = {key:value for key, value in state.items() if class_name not in key}
                return new_items
            except KeyError:
                pass
            return state
    

    And inherit this one in the class requires no private property serialization

    class Availability(jsonpickle.SetGetState):
        pass
    

提交回复
热议问题