Serialize the @property methods in a Python class

后端 未结 5 1606
無奈伤痛
無奈伤痛 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:23

    The solution worked well that is proposed by M. Rafay Aleem and Wtower, but it's duplicated lot of code. Here is an improvment:

    from django.core.serializers.base import Serializer as BaseSerializer
    from django.core.serializers.python import Serializer as PythonSerializer
    from django.core.serializers.json import Serializer as JsonSerializer
    
    class ExtBaseSerializer(BaseSerializer):
    
        def serialize_property(self, obj):
            model = type(obj)
            for field in self.selected_fields:
                if hasattr(model, field) and type(getattr(model, field)) == property:
                    self.handle_prop(obj, field)
    
        def handle_prop(self, obj, field):
            self._current[field] = getattr(obj, field)
    
        def end_object(self, obj):
            self.serialize_property(obj)
    
            super(ExtBaseSerializer, self).end_object(obj)
    
    
    class ExtPythonSerializer(ExtBaseSerializer, PythonSerializer):
        pass
    
    
    class ExtJsonSerializer(ExtPythonSerializer, JsonSerializer):
        pass
    

    How to use it:

    ExtJsonSerializer().serialize(MyModel.objects.all(), fields=['field_name_1', 'property_1' ...])
    

提交回复
热议问题