我目前在我的项目中使用GeoDjango的PointField,并希望为该字段创建自己的字段级验证,因为我希望用户能够输入字符串,例如' 30,10'将字符串更改为" Point(30,10)"该领域需要。
我目前的模特:
class Location(models.Model):
name = models.CharField(max_length=255)
geopoint = PointField(
null=True,
blank=True,
max_length=255,
default=None,
我的序列化器:
class LocationSerializer(serializers.ModelSerializer):
"""
Location serializer class
"""
def validate_geopoint(self,value):
# whole code block doesnt run
import ipdb
ipdb.set_trace()
split_value = value.split(',')
lat = int(split_value[0])
long = int(split_value[1])
point = Point(long,lat)
return point
# pylint: disable=too-few-public-methods
class Meta(object):
"""
Meta options for LocationSerializer
"""
model = Location
fields = [
'id',
'name',
'country',
'geopoint',
'radius',
'shapefile',
'parent',
'created',
'modified'
]
尝试将def validate_name(self,value)添加到Serializer中,其中包含ipdb语句,这似乎已经运行,但def validate_geopoint根本没有运行。
测试:
serialize = LocationSerializer(data=data)
serialize.is_valid()
serialize.errors
然后我收到了这个错误:
{'geopoint': [ErrorDetail(string='Unable to convert to python object: String input unrecognized as WKT EWKT, and HEXEWKB.', code='invalid')]}
答案 0 :(得分:0)
尝试重命名验证器方法:
def validate_geopoint(self,value):
...
为:
def validate(self, value):
...
这应该注意运行它,django_rest_framework并没有完全遵循相同的逻辑形式。但我认为最好的想法是验证models.py中的输入。