[Answered ]-Returning result of a query

2👍

Django model instances and QuerySets are probably not (json) serializable (I never tried). For example, how would it serialize a foreign key or ManyToMany relation?

My solution would be to serialize those attributes that are relevant, e.g.

jsonString = json.dumps([dict(name=p.name, score=p.score)
                         for p in Player.objects.filter(name=namepost)
                        ])

(Just making some assumptions about the fields in your Player model here – adjust it to the actual definition, of course)

If you need to follow references, you can follow them, for example

jsonString = json.dumps([dict(name=p.name, score=p.score, organization=p.org.name)
                         for p in Player.objects.filter(name=namepost)
                        ])

Alternatively, you could implement a serialize() on your models and invoke those recursively:

class Organization(models.Model):
    def serialize(self):
        return dict(name=self.name, address=self.address)

class Player(models.Model):
    def serialize(self):
        return dict(name=self.name, score=self.score, organization=self.org.serialize())

and then json.dumps the serialized dict:

jsonString = json.dumps([p.serialize() for p in Player.objects.filter(name=namepost)])

Leave a comment