0

I have following django model:

class Weather(models.Model):

    lat_lng = gis_models.PointField()
    raw_data = psql_fields.JSONField(null=True)

I have following view:

def weather(request):
    data = WeatherModel.objects.all()
    js_data = serializers.serialize('json', data)
    return HttpResponse(js_data, content_type='application/json')

It throws error saying 'Point object is not json serializable.' I want this function to return json. Please help.

anny
  • 73
  • 1
  • 9
  • 1
    Does this answer your question? [django json serializer does not implement geojson](https://stackoverflow.com/questions/4234540/django-json-serializer-does-not-implement-geojson) – Brown Bear Apr 06 '20 at 06:23

2 Answers2

0

The default JSON serializer doesn't know how to serialize Point objects.

Derive your own from Django's encoder. You can also use JsonResponse for shorter code:

from django.contrib.gis.geos import Point
from django.core.serializers.json import DjangoJSONEncoder
from django.http import JsonResponse


class GeoJSONEncoder(DjangoJSONEncoder):
    def default(self, obj):
        if isinstance(obj, Point):
            return obj.coords
        return super().default(obj)


def weather(request):
    data = WeatherModel.objects.all()
    return JsonResponse(data, encoder=GeoJSONEncoder)
AKX
  • 152,115
  • 15
  • 115
  • 172
  • Thanks for the response but it does not seem to work, at first it says queryset object is not serializable, I converted it to list(WeatherModel.objects.all()) now it asks to add safe=False After that it says Weather object is not serialiazable. – anny Apr 06 '20 at 12:15
0

You can use JsonResponse with values.

from django.http import JsonResponse

def weather(request):
    data = list(WeatherModel.objects.all())
    js_data = serializers.serialize('json', data)
    return JsonResponse(data, safe=False)  # or JsonResponse({'data': data})

Modifed answer from here.

zypro
  • 1,158
  • 3
  • 12
  • 33