如何重写GeoDjango GeoJSON Seriliazer以包括模型属性

时间:2018-07-24 22:45:33

标签: django geojson geodjango django-serializer

这是通用的我如何在JSON序列化中包括属性的分支,请在此处回答:https://stackoverflow.com/a/38253327/4140357

from django.core.serializers.base import Serializer as BaseSerializer
from django.core.serializers.python import Serializer as PythonSerializer
from django.core.serializers.json import Serializer as JsonSerializer

class ExtBaseSerializer(BaseSerializer):

    def serialize_property(self, obj):
        model = type(obj)
        for field in self.selected_fields:
            if hasattr(model, field) and type(getattr(model,
                field)) == property:
                    self.handle_prop(obj, field)

    def handle_prop(self, obj, field):
        self._current[field] = getattr(obj, field)

    def end_object(self, obj):
        self.serialize_property(obj)

        super(ExtBaseSerializer, self).end_object(obj)


class ExtPythonSerializer(ExtBaseSerializer, PythonSerializer):
    pass


class ExtJsonSerializer(ExtPythonSerializer, JsonSerializer):
    pass

如何使用它:

ExtJsonSerializer().serialize(
    MyModel.objects.all(),
    fields=['field_name_1', 'property_1' ...]
)

它非常适合JSON。

如何为GEODJango's GEJSON serializer做同样的事情?

1 个答案:

答案 0 :(得分:0)

更改用于JSON的原始答案以与GEOJSON配合使用非常简单。

您需要在导入中更改一行,因此无需导入 from django.core.serializers.json import Serializer as JsonSerializer导入了一个GEOJSON from django.contrib.gis.serializers.geojson import Serializer as JsonSerializer

这是简化剪切粘贴的完整代码。

from django.core.serializers.base import Serializer as BaseSerializer
from django.core.serializers.python import Serializer as PythonSerializer
from django.contrib.gis.serializers.geojson import Serializer as JsonSerializer


class ExtBaseSerializer(BaseSerializer):

    def serialize_property(self, obj):
        model = type(obj)
        for field in self.selected_fields:
            if hasattr(model, field) and type(getattr(model,
                field)) == property:
                    self.handle_prop(obj, field)

    def handle_prop(self, obj, field):
        self._current[field] = getattr(obj, field)

    def end_object(self, obj):
        self.serialize_property(obj)

        super(ExtBaseSerializer, self).end_object(obj)


class ExtPythonSerializer(ExtBaseSerializer, PythonSerializer):
    pass


class ExtJsonSerializer(ExtPythonSerializer, JsonSerializer):
    pass

如何使用它:

ExtJsonSerializer().serialize(
    MyModel.objects.all(),
    fields=['field_name_1', 'property_1' ...]
)