Error with django-geoposition/json-response

662 views Asked by At

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')
2

There are 2 answers

3
che On BEST ANSWER

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.

0
Robson Alves On

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

on serializers.py put this:

position = serializers.CharField(max_length=100)