将模型函数传递给GeoDjango中的geojson序列化器

时间:2018-11-17 14:33:41

标签: python django geojson django-serializer

问题描述

好吧,我尝试在使用geojson序列化程序成功进行序列化后,将模型(称为Highway)中定义的函数添加到模型(Highway)的HttpResponse中。

由于没有传递任何错误并且该属性未出现在HttpResponse中,因此我试图通过遍历源代码来查找解决方案。但是,我可能会使事情变得复杂,并希望可以对此有所关注。我愿意接受其他建议,也许每次添加/修改位置时都要更新“高速公路”。

将该项目传递到管理站点时正确显示,并且所有其他字段(以下未显示)均按预期工作。

PS。我是整个Django系统的新手。谢谢!

Django版本:2.1

相关链接:

  1. https://docs.djangoproject.com/en/2.1/ref/contrib/gis/serializers/
  2. https://github.com/django/django/blob/master/django/contrib/gis/serializers/geojson.py

最小代码

geom.models.py

class Highway(models.Model):

    name = models.CharField(max_length=50, unique=True)
    length = models.IntegerField("Length in meters")
    mline = models.MultiLineStringField("Geometry", srid=4326)

    def cameras_per_km(self):
        #THIS IS THE FUNCTION I AM TRYING TO SEND TO GEOJSON SERIALIZER
        count = self.location_set.filter(location__icontains="camera").count()
        return round(count/(self.length/1000),1)
    cameras_per_km.short_description = "Cameras/km"


class Location(models.Model):

    location = models.CharField(max_length=30, unique=True)
    highway = models.ForeignKey(Highway, null=True, on_delete=models.SET_NULL)
    point = models.PointField()

geom.admin.py (将功能传递到list_display时,该项目在admin中显示为正确)

class HighwayAdmin(LeafletGeoAdmin):
    list_display = ('name', 'cameras_per_km')

admin.site.register(
    Highway, 
    HighwayAdmin, 
)

geom.views.py (不是)

def geojson_highway_all(request):

    geojsonformat = serialize('geojson', 
          Highway.objects.all(),
          geometry_field='mline',
          fields = (
            'pk',
            'cameras_per_km'  # <-- I want this to show
          )
    )

    return HttpResponse(geojsonformat)

geom.urls.py

from django.urls import path
from . import views

app_name = 'geom'

urlpatterns = [
    path('highways.geojson', views.geojson_highway_all, name='highways.geojson'),
]

1 个答案:

答案 0 :(得分:1)

更新:我(Anton vBR)现在已经完全重写了此答案,但认为@ruddra应该得到一些荣誉。但是,我愿意接受其他解决方案。希望这个答案可以在将来帮助某个人。


基于geojson序列化器创建新的序列化器

geom.views.py

from django.contrib.gis.serializers.geojson import Serializer 

class CustomSerializer(Serializer):

    def end_object(self, obj):
        for field in self.selected_fields:
            if field == self.geometry_field or field == 'pk':
                continue
            elif field in self._current.keys():
                continue
            else:
                try:
                    self._current[field] = getattr(obj, field)()
                except AttributeError:
                    pass
        super(CustomSerializer, self).end_object(obj)

geojsonformat = CustomSerializer().serialize(
      Highway.objects.all(),
      geometry_field='mline',
      fields = (
        'pk',
        'cameras_per_km'
      )