Serialize the @property methods in a Python class

后端 未结 5 1604
無奈伤痛
無奈伤痛 2020-12-01 09:54

Is there a way to have any @property definitions passed through to a json serializer when serializing a Django model class?

example:

class FooBar(obj         


        
5条回答
  •  生来不讨喜
    2020-12-01 10:09

    You can get all of the properties of a class using some black magic:

    def list_class_properties(cls):
        return [k for k,v in cls.__dict__.iteritems() if type(v) is property]
    

    For example:

    >>> class Foo:
           @property
           def bar(self):
               return "bar"
    
    >>> list_class_properties(Foo)
    ['bar']
    

    Then you can build the dictionary and serialize it from there.

提交回复
热议问题