2017-03-03 127 views
0

更新SQLAlchemy的過濾器時區

@datetime_as_timestamp.expression 
def datetime_as_timestamp(cls): 
    return db.func.timestamp(cls.date, cls.time) 

@datetime_as_timestamp.expression 
def datetime_as_timestamp(cls): 
    return cls.date + cls.time 

原始

我有日期和時間在我的模型。在另一個表中有他們的時區,但爲了簡單起見,我會手動完成。我想按日期+時間+時區過濾。

class Foo(db.Model): 
    id = db.Column(db.Integer, primary_key=True) 
    date = db.Column(db.Date) 
    time = db.Column(db.Time) 

    @hybrid_property 
    def datetime_as_timestamp(self): 
     return time.mktime(
      datetime.datetime.combine(self.date, self.time).timetuple() 
     ) 

    @datetime_as_timestamp.expression 
    def datetime_as_timestamp(cls): 
     return db.func.timestamp(cls.date, cls.time) 

但是,當我執行過濾查詢

In [1]: Foo.query.filter(func.timezone('Australia/Brisbane', Foo.datetime_as_timestamp) <= func.timezone('UTC', func.current_timestamp())).one() 

我得到一個錯誤

psycopg2.ProgrammingError) syntax error at or near "foo" 
LINE 3: WHERE timezone('Australia/Brisbane', timestamp(foo.da... 
               ^
[SQL: 'SELECT foo.id AS checkin_flight_id, foo.date AS checkin_flight_date, foo.time AS checkin_flight_time \nFROM foo \nWHERE timezone(%(timezone_1)s, timestamp(foo.date, foo.time)) <= timezone(%(timezone_2)s, CURRENT_TIMESTAMP)'] [parameters: {'timezone_2': 'UTC', 'timezone_1': 'Australia/Brisbane'}] 

我缺少什麼,哪裏是我的錯?是否有可能以另一種方式解決我的問題?

回答

0

我發現這個Q&A非常有幫助。我改變

@datetime_as_timestamp.expression 
def datetime_as_timestamp(cls): 
    return db.func.timestamp(cls.date, cls.time) 

@datetime_as_timestamp.expression 
def datetime_as_timestamp(cls): 
    return cls.date + cls.time 

和一切工作正常