好的,在使用geojson序列化程序序列化之后,我尝试将模型(称为Highway)中定义的函数添加到模型(Highway)的HttpResponse中,但没有成功。
我试图通过查看源代码来找到解决方案,因为没有传递任何错误,并且该属性没有出现在HttpResponse中。但是我可能
希望我们能重新审视这件事。我愿意接受其他建议,也许每次添加/修改位置时都会更新高速公路。
当将项目传递到管理站点时,它会正确显示,并且所有其他字段(下面未显示)都能正常工作。
Django版本:2.1
-
https://docs.djangoproject.com/en/2.1/ref/contrib/gis/serializers/
-
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'),
]