Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize to JSON a list of model objects in django/python

Tags:

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.

like image 250
gc5 Avatar asked Oct 23 '12 13:10

gc5


People also ask

How do you serialize a Queryset?

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.

How do you serialize a JSON in Python?

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.

What is serializing and Deserializing in Django?

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.


1 Answers

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") 
like image 133
Martijn Pieters Avatar answered Sep 23 '22 18:09

Martijn Pieters