我有一個包含IP地址範圍的模型,與此類似:在App Engine數據存儲上等價的查詢之間?
class Country(db.Model):
begin_ipnum = db.IntegerProperty()
end_ipnum = db.IntegerProperty()
在一個SQL數據庫,我就可以找到它包含一個IP在一定範圍內是這樣行:
SELECT * FROM Country WHERE ipnum BETWEEN begin_ipnum AND end_ipnum
或本:
SELECT * FROM Country WHERE begin_ipnum < ipnum AND end_ipnum > ipnum
可悲的是,GQL只允許在一個屬性不等式過濾器,並且不支持BETWEEN
語法。我該如何解決這個問題並在App Engine上構建與這些查詢等效的查詢?
另外,是否可以將ListProperty
設置爲「有效」,或者在記錄創建時是否需要計算?
問題的解決與第一刺更新:
因此,基於大衛的回答下面和物品,如這些:
http://appengine-cookbook.appspot.com/recipe/custom-model-properties-are-cute/
我想添加自定義字段對我的模型是這樣的:
class IpRangeProperty(db.Property):
def __init__(self, begin=None, end=None, **kwargs):
if not isinstance(begin, db.IntegerProperty) or not isinstance(end, db.IntegerProperty):
raise TypeError('Begin and End must be Integers.')
self.begin = begin
self.end = end
super(IpRangeProperty, self).__init__(self.begin, self.end, **kwargs)
def get_value_for_datastore(self, model_instance):
begin = self.begin.get_value_for_datastore(model_instance)
end = self.end.get_value_for_datastore(model_instance)
if begin is not None and end is not None:
return range(begin, end)
class Country(db.Model):
begin_ipnum = db.IntegerProperty()
end_ipnum = db.IntegerProperty()
ip_range = IpRangeProperty(begin=begin_ipnum, end=end_ipnum)
思想是,我添加了習慣米財產我可以導入我的數據集是再基於該的ListProperty像這樣運行查詢:
q = Country.gql('WHERE ip_range = :1', my_num_ipaddress)
當我嘗試插入新的國家反對這種失敗雖然complaning有關無法創建名稱:
...
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/db/__init__.py", line 619, in _attr_name
return '_' + self.name
TypeError: cannot concatenate 'str' and 'IntegerProperty' objects
我試圖定義一個attr_name
法新屬性或只設置self.name
但似乎並沒有幫助。絕望地卡住或朝着正確的方向前進?
錯誤是dev_appserver執行的方式,不幸的是:正確的行爲是當前的生產行爲。 – 2010-07-27 08:46:36
這看起來像一個有前途的解決方案,很好,很簡單。從文檔看來,我可以根據begin_ipnum和end_ipnum的值創建一個自定義模型屬性,用於報告列表值'live'。但據我所知,我無法使用GQL查詢定製屬性。所以我會首先嚐試一個計算ListProperty的值來創建對象的範圍。將報告我的票價! – tijs 2010-07-27 08:51:31