【问题标题】:<Django Object>: is not JSON serializable<Django 对象>:不是 JSON 可序列化的
【发布时间】:2014-10-23 04:54:28
【问题描述】:

这是我的看法:

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

idclandpin 不是外键,而是ssectionid

那么,如何序列化外键呢?

【问题讨论】:

    标签: json django


    【解决方案1】:

    你可以像这样使用序列化器类:

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

    如果您只想序列化几个字段,请执行以下操作:

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

    其中 fieldname1 和 fieldname2 是土地属性模型类的属性。

    或者,您可以为您的土地属性类编写一个自定义序列化程序,并在调用渲染时使用它。

    【讨论】:

    • 谢谢!我试过了,但它返回了一个错误,'str' object has no attribute 'transform'
    • 你可以检查query_agao是否是一个queryset对象(它不应该是一个单一的模型对象),如果你能发布堆栈跟踪将会很有帮助。
    猜你喜欢
    • 2013-05-23
    • 2015-02-24
    • 2018-09-12
    • 2014-09-21
    • 1970-01-01
    • 2016-04-01
    • 2012-07-02
    • 1970-01-01
    • 2020-03-04
    相关资源
    最近更新 更多