I am trying to serialize a list of model object defined as:
class AnalysisInput(models.Model): input_user = models.CharField(max_length=45) input_title = models.CharField(max_length=45) input_date = models.DateTimeField() input_link = models.CharField(max_length=100)
I wrote a custom serializer (encoder) for json.dumps():
class AnalysisInputEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, AnalysisInput): return { "input_id" : obj.id, "input_user" : obj.input_user, "input_title" : obj.input_title, "input_date" : obj.input_date.isoformat(), "input_link" : obj.input_link } return json.JSONEncoder.default(self, obj)
When I serialize only one object, I am able to do it. When I try to serialize a list of object I get
[ objects..] is not JSON serializable
I searched but I didn't find where to work on.. I was thinking about writing a custom serializer also for list of model object.
To serialize a queryset or list of objects instead of a single object instance, you should pass the many=True flag when instantiating the serializer. You can then pass a queryset or list of objects to be serialized.
The json module exposes two methods for serializing Python objects into JSON format. dump() will write Python data to a file-like object. We use this when we want to serialize our Python data to an external JSON file. dumps() will write Python data to a string in JSON format.
Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.
A custom encoder is not called recursively. You are actually better off not using a custom encoder, and instead convert your objects to simple python types before serializing.
You could add a as_json
or similarly named method to your model and calling that every time you need a JSON result:
class AnalysisInput(models.Model): input_user = models.CharField(max_length=45) input_title = models.CharField(max_length=45) input_date = models.DateTimeField() input_link = models.CharField(max_length=100) def as_json(self): return dict( input_id=self.id, input_user=self.input_user, input_title=self.input_title, input_date=self.input_date.isoformat(), input_link=self.input_link)
Then in your view:
# one result return HttpResponse(json.dumps(result.as_json()), content_type="application/json") # a list of results results = [ob.as_json() for ob in resultset] return HttpResponse(json.dumps(results), content_type="application/json")
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