2

I'm doing an autocomplete input.

I'm trying to create a json response. In my model I have this:

   position = GeopositionField(default=DEFAULT)

When I try to create the json response gives me this error:

   TypeError: Geoposition(40,2) is not JSON serializable

How could I fix this ?

Edit 1:

In views.py:

data =[{'label': n.nombre, 'nombre': n.nombre, 'posicion': n.position, 'status': n.estado} for n in
               Dispositivo.objects.filter(nombre__icontains=what)]

return HttpResponse(json.dumps(data), mimetype='application/json')
Don
  • 292
  • 2
  • 12

2 Answers2

4

The problem is pretty much the what the exception says. GeopositionField is a complex type, which does not have any standard way of serializing to JSON. You have to split it up into individual coordinates, for example by convertion it to a dictionary in your model.

Like this:

class Dispositivo(models.Model):
    ...

    def position_dict(self):
        return {'lat': self.position.latitude, 'lon': self.position.longitude}

And then in data you're dumping, write {... 'position': n.position_dict(), ...} to use the dictionary representation instead of the complex field.

che
  • 12,097
  • 7
  • 42
  • 71
  • Thanks for helping. Now, how can I serialize a decimal?I tried `Decimal(n.position.latitude)` in data and didn't work.I could to serialize converting to a string `str(n.position.latitude)` – Don Nov 12 '13 at 08:50
  • How can I use `position_dict` in a query like that: `a=Dispositivo.objects.filter(bla='bla').values(...,position_dict.lat,position_dict.lon)` – Don Nov 12 '13 at 12:46
  • @Don: I don't think you can. – che Nov 12 '13 at 19:58
1

I solved this problem just by putting CharField when serializer on GeopositionField

on serializers.py put this:

position = serializers.CharField(max_length=100)
Robson Alves
  • 74
  • 1
  • 5