2013-03-12 46 views
0

在谷歌應用引擎上,我想知道是否有可能在ndb查詢中構建條件的方式如下所述。假設我有以下代碼:谷歌應用引擎:ndb查詢更清潔

if bidded == '': 
    productRanks = Product.query(Product.bidTime>=startDate, 
           Product.bidTime<endDate).fetch()   
elif bidded == 'yes': 
    productRanks = Product.query(Product.bidTime>=startDate 
           Product.bidTime<endDate, 
           Product.bidded=='yes').fetch() 
else: 
    productRanks = Product.query(Product.bidTime>=startDate 
           Product.bidTime<endDate, 
           Product.bidded=='no').fetch() 

它看起來非常混亂。假設,我希望能夠做到以下幾點。可能嗎?如果是,如何?

condition = 'Product.bidTime>=startDate, Product.bidTime<endDate' 
if bidded = 'yes': 
    condition = condition + ', Product.bidded=='yes' 
elif bidded == 'no': 
    condition = condition + ', Product.bidded=='no' 
productRanks = Product.query(condition).fetch() 

回答

2

你真的應該花一些時間閱讀文檔,它會爲你節省很多時間。

請參閱https://developers.google.com/appengine/docs/python/ndb/queries#filter_by_prop如果您閱讀本節,則清楚地表明您可以繼續添加過濾器。從文檔來看,這個例子非常清楚。

qry1 = Account.query() # Retrieve all Account entitites 
qry2 = qry1.filter(Account.userid >= 40) # Filter on userid >= 40 
qry3 = qry2.filter(Account.userid < 50) # Filter on userid < 50 as well 

而且您不必一直創建新的查詢,只需重新綁定相同的變量即可。

+0

謝謝。但另一個問題是:當我在不同的字段上執行過濾時,我收到錯誤消息_「每個查詢只支持一個不等式過濾器。遇到了兩個......」_ – 2013-03-12 09:43:22

+0

That's correct。該錯誤消息反映了數據存儲的查詢功能的限制。您可能需要更改模型以在寫入時混合各種值,以使您想要的查詢成爲可能。 – 2013-03-12 09:49:36

+1

它可能還會支付查看搜索API,並查看哪些查詢可能存在。 – 2013-03-12 09:51:45