问题描述
如何在elasticsearch django中定义GeoPointField().当我尝试保存实例时,它显示序列化错误.我正在使用库"django_elasticsearch_dsl代码:
How to define GeoPointField() in elasticsearch django. It shows a serialization error when i am trying to save the instance. i am using library "django_elasticsearch_dslcode:
from django_elasticsearch_dsl.fields import GeoPointField
geolocation = GeoPointField()
当我尝试保存数据时
user = GutitUser.objects.get(phone_number=phone_number)
lat, lon = get_lat_long()
user.geolocation.lat = lat
user.geolocation.lon = lon
user.save()
显示错误:
"Unable to serialize <django_google_maps.fields.GeoPt object at 0x7f5ac2daea90>
(type: <class 'django_google_maps.fields.GeoPt'>
get_lat_long方法
get_lat_long method
def get_lat_long(request):
ip = json.loads(requests.get('https://api.ipify.org?format=json').text)['ip']
lat, lon = GeoIP().lat_lon(ip)
return lat, lon
推荐答案
问题是django_elasticsearch_dsl
(还有elasticsearch_dsl
)不知道如何将自定义django_google_maps.fields.GeoPt
对象序列化为可理解的格式Elasticsearch.
The problem is that django_elasticsearch_dsl
(and further, elasticsearch_dsl
) doesn't know how to serialize that custom django_google_maps.fields.GeoPt
object into a format understood by Elasticsearch.
引用 docs ,该对象将需要有一个to_dict()
方法.
Quoting the docs, the object will need to have a to_dict()
method.
您应该能够使用(干编码)之类的东西来猴子修补该方法
You should be able to monkey-patch that method in with something like (dry-coded)
from django_google_maps.fields import GeoPt
GeoPt.to_dict = lambda self: {'lat': self.lat, 'lon': self.lon}
在应用程序代码中的较早位置(例如,AppConfig ready()
方法是一个不错的选择,否则,例如models.py
是一个失败的选择)
early in your app's code (an AppConfig ready()
method is a good choice, or failing that, a models.py
, for instance)
这篇关于如何为Elasticsearch序列化Django GeoPt的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!