很难为这个线程找到一个好的标题。我正在使用 django、geodjango (postgis)、django-rest-framework 和 rest_framework_gis 开发 Web 服务。这些网络服务将用于交互式地图。
我的模型之一如下:
class Polygon(models.Model):
fk_owner = models.ForeignKey(User, on_delete=models.DO_NOTHING) # the owner of this polygon (User)
external_id = models.CharField(max_length=25) # id in data warehouse
func_type = models.CharField(max_length=15) # e.g 'field', 'building', ...
coordinates = models.PolygonField()
properties = JSONField(default={}) # JSON containing attributes and actions
该模型的序列化器:
class PolygonSerializer(GeoFeatureModelSerializer):
class Meta:
model = Polygon
geo_field = "coordinates"
fields = ('external_id', 'fk_owner', 'func_type', 'properties')
和端点
class FieldList(generics.ListCreateAPIView):
serializer_class = PolygonSerializer
lookup_field = 'external_id'
lookup_url_kwarg = 'external_id_field'
def get_queryset(self):
id_user = User.objects.get(external_id=self.kwargs['external_id_user']).id
queryset = Polygon.objects.filter(func_type="field").filter(fk_owner=id_user).all()
return queryset
def perform_create(self, serializer):
user = User.objects.get(external_id=self.kwargs['external_id_user'])
serializer.save(fk_owner=user)
当我使用以下 curl 请求时:
curl -X POST http://xxx.yyy.zzz/api/v2/users/aZ523AsZm/fields/ -d '{"external_id": "aE15feg64AzaP", "func_type": "field", "coordinates": "POLYGON((62780.8532226825 5415035.177460473, 62941.3759284064 5415283.89540161, 63187.058044587146 5415364.391565912, 63257.96856022246 5414992.852982632, 62780.8532226825 5415035.177460473, 62780.8532226825 5415035.177460473))", "properties": {"a": "b"}}' -H "Content-Type: application/json"
我明白了{"fk_owner":["This field is required."],"external_id":["This field is required."],"coordinates":["This field is required."],"func_type":["This field is required."]}
但是,当我用一个简单的 ModelSerializer 替换 GeoFeatureModelSerializer 时,一切都很好。为什么 ?
我花了大约 1 个小时才找到有罪的人,我的一天工作很快就结束了。任何帮助将不胜感激!谢谢,很抱歉这么长的帖子。
[编辑 10/11]:我的解决方法是使用 2 个序列化程序:一个用于 GET,一个用于 CREATE 类 PolygonList(generics.ListCreateAPIView): queryset = Point.objects.all() filter_backends = (drfg_filters.InBBoxFilter,)
def get_serializer_class(self):
if self.request.method == 'POST':
self.serializer_class = PolygonSerializerCreate
if self.request.method == 'GET':
self.serializer_class = PolygonSerializerRetrieve
return self.serializer_class