Serialize the @property methods in a Python class

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

    You can extend Django's serializers without /too/ much work. Here's a custom serializer that takes a queryset and a list of attributes (fields or not), and returns JSON.

    from StringIO import StringIO
    from django.core.serializers.json import Serializer
    
    class MySerializer(Serializer):
        def serialize(self, queryset, list_of_attributes, **options):
            self.options = options
            self.stream = options.get("stream", StringIO())
            self.start_serialization()
            for obj in queryset:
                self.start_object(obj)
                for field in list_of_attributes:
                    self.handle_field(obj, field)
                self.end_object(obj)
            self.end_serialization()
            return self.getvalue()
    
        def handle_field(self, obj, field):
            self._current[field] = getattr(obj, field)
    

    Usage:

    >>> MySerializer().serialize(MyModel.objects.all(), ["field1", "property2", ...])
    

    Of course, this is probably more work than just writing your own simpler JSON serializer, but maybe not more work than your own XML serializer (you'd have to redefine "handle_field" to match the XML case in addition to changing the base class to do that).

提交回复
热议问题