Helio
Helio

Reputation: 81

Returning result of a query

I am not able to return the result of a query. So this is what I'm doing is:

Código (Python):

def filter(request):
    if request.method == 'POST':
        namepost = request.POST.get('name')
        print namepost
        result = Player.objects(name=namepost)
        print result
        # for n in result:
        #    print n.surname
        # jsonString = json.dumps(result)
    return HttpResponse(content_type='application/json')

I'm making a query to get the name on the post, and wanted to return the result, but I am not getting ... The result gives me the following: [] Json.dumps tried with me but says: [] is not JSON serializable

How can I return the query result?

Upvotes: 1

Views: 85

Answers (1)

Jonas Reichert
Jonas Reichert

Reputation: 118

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

Upvotes: 2

Related Questions