2012-10-10 83 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模型,但我不知道任何其他轉換方法。 –

相關問題