2015-09-28 64 views
4

所以重寫關係定義的「ORDER_BY」,我有一個模型,它是這樣的:的SQLAlchemy:在查詢

class Foo(model): 
    __tablename__ = "foo" 
    id = Column(Integer, primary_key=True) 
    data = relationship(
     "FooData", 
     cascade="all, delete-orphan", 
     backref="foo", 
     lazy="dynamic", 
     order_by="desc(FooData.timestamp)" 
    ) 

    @property 
    def first_item(self): 
     # the problem is here: 
     return self.data.order_by(asc("timestamp")).first() 

    @property 
    def latest_item(self): 
     return self.data.first() 


class FooData(Model): 
    __tablename__ = "foo_data" 
    foo_id = Column(Integer, ForeignKey("foo.id"), primary_key=True) 
    timestamp = Column(DateTime, primary_key=True) 
    actual_data = Column(Float, nullable=False) 

那麼,問題出在first_item方法有:當如上述定義中,SQL看起來像這樣:

SELECT foo_data.timestamp AS foo_data_timestamp, foo_data.actual_data AS foo_data_actual_data, foo_data.foo_id AS foo_data_foo_id 
FROM foo_data 
WHERE :param_1 = foo_data.foo_id ORDER BY foo_data.timestamp DESC, foo_data.timestamp ASC 
--                 ^^^^^^^^^^^^^^^^^^^^^^ 

顯然,在查詢中指定的order_by被附加到在關係定義中指定的一個,而不是替換它;有沒有辦法讓查詢覆蓋原來的order_by?我知道我可以直接在FooData類上指定一個單獨的查詢,但如果可能的話,我想避免這種查詢。

回答

4

根據documentation

所有現有的ORDER BY設置可以通過傳遞None被抑制 - 這將抑制任何ORDER BY上映射器配置爲好。

所以簡單的解決方案是重置ORDER BY子句,然後應用你需要的。像:

self.data.order_by(None).order_by(asc("timestamp")).first() 

如果你不想重置整個ORDER BY條款,而只是想覆蓋一個列的順序,據我所知有沒有爲它的內置方式。

+0

謝謝,這是它!我注意到其他答案中提到了這種技術,但我從來沒有想過在這裏使用它。 –