<Point 对象在 XXX> 不能序列化为 JSON

0 投票
1 回答
1948 浏览
提问于 2025-04-17 20:46

我在使用Django 1.6、Python 3.3和haystack时遇到了一个问题。简单来说,我想在haystack中使用LocationField,但不太成功。

这是Python抛出的异常。

<Point object at 0x7fe54e41d9a0> is not JSON serializable

这是我在search_indexes.py中的代码:

class ListingIndex(indexes.SearchIndex, indexes.Indexable):
    ....
    location = indexes.LocationField(model_attr='get_location')
    ....

    def get_model(self):
        return Listing

还有在models.py()中的代码:

...
from haystack.utils.geo import Point
...

class Listings(models.Model):
    ...
    def get_location(self):
        return Point(self.lng, self.lat)

我在谷歌和StackOverflow上搜索了好几个小时,学习了很多关于序列化Django对象的知识,但还是没有找到能帮我解决这个问题的结果。提前谢谢大家。

1 个回答

0

我在这里找到了我的解决办法。问题出在我更新Elasticsearch的时候,给位置点对象传递参数(因为这个字段是位置类型,我以为这样做是对的),但实际上,我应该传递一个json格式的数据。下面是代码:

location = self.get_location()
location_es = "{0},{1}".format(location.y, location.x)

然后在更新Elasticsearch的时候,我使用的是location_es,而不是location作为位置字段的参数。谢谢大家的回答! :)

撰写回答