2012-10-10 43 views
0

我正在使用Python在Google App Engine上编写网站,并且我有一个位置数据存储区实体,该实体具有包含GPS坐标的字符串属性。我想让用户通过GPS坐标搜索,并且我想返回纬度或经度+/- 10点内的所有位置。基本上我想要做的是在下面的代码,但我不能这样排序GPS,一个因为它是一个字符串和两个,因为它是相同的属性。通过GPS位置对数据库查询进行排序

inputlocation = self.request.get("userlocation") 

     g = geocoders.Google() 
     try: 
      place, (lat, lng) = g.geocode(inputlocation) 
     except ValueError: 
      geocodespot = g.geocode(inputlocation, exactly_one=False) 
      place, (lat, lng) = geocodespot[0] 
     GPSlocation = "("+str(lat)+", "+str(lng)+")" 
     GPSlocation = float(GPSlocation) 

     bound = 10 
     upper = GPSlocation + bound 
     lower = GPSlocation - bound 
     left = GPSlocation + bound 
     right = GPSlocation - bound 

     if GPSlocation: 
      locations = db.GqlQuery("select * from Location where GPSlocation>:1 and where GPSlocation>:2 and where GPSlocation <:3 and where GPSlocation <:4 order by created desc limit 20", upper, lower, left, right) 
#example GPSlocation in the datastore = "(37.7699298, -93.4469157)" 

你能想到的任何方式基本上是这样做,而不必更改数据存储区设置的方式吗?有没有什么方法可以在不为Latitude和Longitude创建两个属性的情况下获取这些信息?

回答

1

也许你想添加一个Computed Property:

https://developers.google.com/appengine/docs/python/ndb/properties#computed

计算属性(ComputedProperty)是只读的,其 值从其他属性值由 应用程序提供的函数来计算的特性。所计算的值被写入到数据存储区 ,以便它可以查询和在数据存储区 查看器中显示,但是当该实体被读回从数据存储 所存储的值将被忽略;相反,只要请求值,就通过调用 函数来重新计算该值。

class SomeEntity(ndb.Model): 
    name = ndb.StringProperty() 
    name_lower = ndb.ComputedProperty(lambda self: self.name.lower()) 

x = SomeEntity(name='Nick') 

所以,你想要某种功能,而不是较低的()以上,其计算然后更新一个新的LatFloat,LongFloat在你的模型。所以你可以将数据保存为两个浮点数以及一个字符串。我相信你可以添加这个,你的现有数据不会受到影响,而当你试图读取或搜索这些数据时,它会被计算并返回。

+0

嗯看起来只是我需要的,但我猜你不能将它用于常规的db类? – clifgray

+0

有没有办法将数据库转换为ndb?或者有没有使用db的优势? – clifgray

+0

啊,你可以用某种更先进的python魔法来做某事。 Ndb似乎提供了许多好处恕我直言,包括计算的属性。 Plus缓存是自动的。你可以写一个后台任务在复制数据到NDB模型,但我不知道任何其他转换方法。 –

相关问题