在Serialize Json和geojson时加入相关数据

时间:2017-02-10 14:47:51

标签: python json django serialization geojson

在Django视图中:

我想加入两个表中的数据。 lease_geom.query提供了正确的查询,但是当我序列化lease_geom时,没有来自相关表格的数据。

def mapdata_leases_geom(request, lic):

    # only one table data
    lease_geom = Ssm_El_Ml_Pl_Blocks.objects.filter(license=lic).select_related()
    q = lease_geom.query
    lease_geom = serialize('geojson', lease_geom,
          geometry_field='geom')
  

该函数只返回第一个表的geojson。

1 个答案:

答案 0 :(得分:0)

经过这么多天的工作后,我找到了解决方案,你可以在django中使用SERIALIZERs类创建自己的 SERIALIZER 。 我发布的解决方案对我有用。

CUSTOMIZED GEOJSON SERIALIZER

from django.utils.encoding import force_text
from django.contrib.gis.serializers.geojson import Serializer as geoSerializer

class geoJsonSerialiser(geoSerializer):

    # ADDING FIELDS TO GEOJSON
    def add_field(self, current, obj):
        current['grant date'] = force_text(obj.lease.grant_date)
        current['expiry date'] = force_text(obj.lease.expiry_date)
        return current

    # OVERRIDING GET_DUMP_OBJECT METHOD IN GEOJSON SERIALIZER

    def get_dump_object(self, obj):
        current = self.add_field(self._current, obj)
        data = {
            "type": "Feature",
            "properties": current,
        }
        if ((self.selected_fields is None or 'pk' in self.selected_fields) and
                    'pk' not in data["properties"]):
            data["properties"]["pk"] = obj._meta.pk.value_to_string(obj)
        if self._geometry:
            if self._geometry.srid != self.srid:
                # If needed, transform the geometry in the srid of the global geojson srid
                if not HAS_GDAL:
                    raise SerializationError(
                        'Unable to convert geometry to SRID %s when GDAL is not installed.' % self.srid
                    )
                if self._geometry.srid not in self._cts:
                    srs = SpatialReference(self.srid)
                    self._cts[self._geometry.srid] = CoordTransform(self._geometry.srs, srs)
                self._geometry.transform(self._cts[self._geometry.srid])
            data["geometry"] = eval(self._geometry.geojson)
        else:
            data["geometry"] = None
        return data

可能对其他人有用