Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize the @property methods in a Python class

Tags:

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

example:

class FooBar(object.Model)      name = models.CharField(...)      @property     def foo(self):         return "My name is %s" %self.name 

Want to serialize to:

[{      'name' : 'Test User',      'foo' : 'My name is Test User', },] 
like image 271
ashchristopher Avatar asked Apr 06 '10 17:04

ashchristopher


People also ask

Can you serialize a class Python?

Instead of making class JSON serializable, we can implement a serializer method in the class. So we don't need to write custom JSONEncoder. This new toJSON() serializer method will return the JSON representation of the Object. i.e., It will convert custom Python Object to JSON string.

Which method is used for serialization in Python?

NumPy Array (flat data) Python's NumPy array can be used to serialize and deserialize data to and from byte representation.

What does it mean to serialize in Python?

Serialization refers to the process of converting a data object (e.g., Python objects, Tensorflow models) into a format that allows us to store or transmit the data and then recreate the object when needed using the reverse process of deserialization.


1 Answers

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).

like image 133
user85461 Avatar answered Sep 21 '22 12:09

user85461