2013-02-18 22 views
2

我有這樣的模式:GAE數據存儲:按日期間隔濾波器

class Vehicle(db.Model): 
    ... 
    start_production_date = db.DateProperty() 
    end_production_date = db.DateProperty() 

我需要過濾,例如,所有的內,比如在生產汽車,2010:

我想我可以這樣做:

q = (Vehicle.all() 
    .filter('start_production_date >=', datetime(2010, 1, 1)) 
    .filter('end_production_date <', datetime(2011, 1, 1))) 

買我得到BadFilterError

BadFilterError: invalid filter: Only one property per query may have inequality filters (<=, >=, <, >).. 

那麼,我該如何實現這個目標呢?而且這在我看來是一個相當普遍的任務。

回答

2

我用這個去解決方案:

我設置在模型a ListProperty項目包含模型製作的所有年份:

vhl.production_years = range(start_production_date.year, end_production_date + 1) 

然後測試:

q = (Vehicle.all() 
    .filter('production_years =', 2010)) 
2

一種方法是將模型更改爲類似這樣:

class Vehicle(db.Model): 
    ... 
    start_production_date = db.DateProperty() 
    start_production_year = db.IntegerProperty() 
    start_production_month = db.IntegerProperty() 
    start_production_day = db.IntegerProperty() 

    end_production_date = db.DateProperty() 
    end_production_year = db.IntegerProperty() 
    end_production_month = db.IntegerProperty() 
    end_production_day = db.IntegerProperty() 

更新每把這些新的值(你可以override put)和簡單:

# specific year 

q = (Vehicle.all() 
    .filter('start_production_year =', 2010)) 

# specific year, different months 

q = (Vehicle.all() 
    .filter('start_production_year =', 2010) 
    .filter('start_production_month IN', [1, 2, 3, 4])) 

# different years 

q = (Vehicle.all() 
    .filter('start_production_year IN', [2010, 2011, 2012])) 
+0

對不起,但這並不解決了這個問題:我如何在生產在2010年篩選模式?那一年是**開始和結束日期之間的**。例如,有些模型在2000年開始建造,並在2012年停產,等等。 – neurino 2013-02-19 15:04:04

+0

@neurino你可以手動創建這些列表,然後使用'IN'運算符。例如,如果'start_list = [2000,2001,2002,2003,2004]'和'end_list = [2009,20010,20011,20012,2013]',您可以使用兩個過濾器:'.filter('start_production_year IN', start_list).filter('end_production_year IN',end_list)' – Lipis 2013-02-19 15:10:33

+0

@neurino我不知道你是否可以找到更好的..因爲你不允許在同一個過濾器中使用兩個不相等的操作符.. – Lipis 2013-02-19 15:11:50