Sachi Tekina
Sachi Tekina

Reputation: 1810

<Django Object>: is not JSON serializable

Here's my view:

def display_maps(request):
#query_agao = ButuanMaps.objects.filter(clandpin=search_term)
#x = Owner.objects.select_related('landproperty_butuanmaps').get(id=5)
query_agao = ButuanMaps.objects.all().select_related('landproperty')[:10]
query_all = ButuanMaps.objects.all()[:10]
djf = Django.Django(geodjango='geom', properties=['id','clandpin','ssectionid'])
geoj = GeoJSON.GeoJSON()
butuan_agao = geoj.encode(djf.decode(query_agao.transform(3857)))
return render(request, "index.html", {
    'butuan_agao': butuan_agao,
    'query_agao': query_agao,
    'query_all': query_all})

id and clandpin are not foreignkey, but ssectionid.

So, how to serialize foreign keys?

Upvotes: 2

Views: 1640

Answers (1)

Shivansh
Shivansh

Reputation: 143

You can use serializers class like this :

from django.core import serializers
query_agao = ButuanMaps.objects.all().select_related('landproperty')[:10]
json_serialized_objects = serializers.serialize("json", query_agao)

if you only want to serialize few fields do this :

json_serialized_objects = serializers.serialize("json", query_agao, fields=("fieldname1", "fieldname2"))

where fieldname1 and fieldname2 are attributes of landproperty model class.

Alternately you can do a write a custom serializer for your landproperty class and use it at the time of calling render.

Upvotes: 2

Related Questions