我不断收到此错误:
TypeError at /
<Section: BILAY - 001> is not JSON serializable
在我看来.py:
def display_maps(request):
pnt = ButuanMaps.objects.get(clandpin='162-03-0001-017-33').geom
query_section = Section.objects.all().order_by('sbrgyid__cbrgyname')
query_soiltype = SoilType.objects.all()
query_maps = ButuanMaps.objects.filter(landproperty__sownerid__id=5, geom__distance_lte=(pnt, D(km=100)),narea__lte =5500000)
djf = Django.Django(geodjango='geom', properties= ['id','clandpin','ssectionid','narea'])
geoj = GeoJSON.GeoJSON()
butuan_agao = geoj.encode(djf.decode(query_maps.transform(3857)))
...
return render(request, "index.html", {
'butuan_agao': butuan_agao,
'query_agao': query_maps,
'query_section': query_section,
'butuan_soil': butuan_soil,
'query_soiltype': query_soiltype
})
在我的 models.py 中:
class ButuanMaps(gismodel.Model):
class Meta:
verbose_name = u'Butuan Map'
verbose_name_plural = u'Butuan Maps'
clandpin = gismodel.CharField("Land PIN", max_length=50, null=True, blank=True)
ssectionid = gismodel.ForeignKey(Section)
narea = gismodel.DecimalField(max_digits=20, decimal_places=6)
#ssectionid_id = gismodel.IntegerField()
geom = gismodel.MultiPolygonField("Geom ID", srid=32651, null=True, blank=True)
objects = gismodel.GeoManager()
def __unicode__(self):
return self.clandpin
当我在属性上添加 narea
和 ssectionid
时,它会返回错误。为什么?在这一行中:
djf = Django.Django(geodjango='geom', properties= ['id','clandpin','ssectionid','narea'])
最佳答案
我在使用 Django.Django - GeoJSON.GeoJSON() 方法时遇到了同样的问题。
错误很清楚,告诉您您的字段“不可 JSON 序列化”。
第一个因为它是小数,所以我猜它不理解你的小数符号,无论它应该是逗号还是点......
第二个,因为它是一个外键并且不能很好地处理它。
对于最后一个问题,我的建议是从 djf 部分中删除该属性,对其进行解码,将属性放回到 类似 json 的字典中,最后进行编码这一切。
1-获取属性
prop = MyModel._meta.get_all_field_names()
2-删除“ssectionid”属性
prop.remove("ssectionid")
3-解码
djf = Django.Django(geodjango='geom', properties = prop)
decod = djf.decode(obj)
4-获取外键值
sectionlist = MyModel.objects.filter().values('ssectionid__id')
5-为“decode”的每个元素添加属性“ssectionid”
for el in decod:
el.to_dict()["properties"].update({"ssectionid": sectionlist.get(id=el.properties['id'])["ssectionid__id"]})
6-编码
geojson = geoj.encode(decod)
我并不是说这是一个很好的答案,我只是说它有效。
编辑
包裹django-geojson就是您正在寻找的!
关于python - 在 GeoDjango 中添加属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25862738/