如何为Elasticsearch序列化Django GeoPt [英] How to serialize Django GeoPt for Elasticsearch

查看:196
本文介绍了如何为Elasticsearch序列化Django GeoPt的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在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_dsl code:

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.

我们使用的序列化程序还将允许您序列化自己的对象-只需在对象上定义一个to_dict()方法,并在序列化为json时将自动调用该方法.

The serializer we use will also allow you to serialize your own objects - just define a to_dict() method on your objects and it will automatically be called when serializing to json.

您应该能够使用(干编码)之类的东西来猴子修补该方法

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆