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', },]
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.
NumPy Array (flat data) Python's NumPy array can be used to serialize and deserialize data to and from byte representation.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With