代码之家  ›  专栏  ›  技术社区  ›  Anton vBR

将模型函数传递给GeoJango中的geojson序列化程序

  •  1
  • Anton vBR  · 技术社区  · 6 年前

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

    我试图通过查看源代码来找到解决方案,因为没有传递任何错误,并且该属性没有出现在HttpResponse中。但是我可能 希望我们能重新审视这件事。我愿意接受其他建议,也许每次添加/修改位置时都会更新高速公路。

    当将项目传递到管理站点时,它会正确显示,并且所有其他字段(下面未显示)都能正常工作。

    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

    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.url.py

    from django.urls import path
    from . import views
    
    app_name = 'geom'
    
    urlpatterns = [
        path('highways.geojson', views.geojson_highway_all, name='highways.geojson'),
    ]
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   Anton vBR    6 年前

    我(Anton vBR)现在已经完全重写了这个答案,但我认为@ruddra应该得到一些赞扬。然而,我是 开放供选择的解决方案 . 希望这个答案能在将来帮助别人。


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