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
類上指定一個單獨的查詢,但如果可能的話,我想避免這種查詢。
謝謝,這是它!我注意到其他答案中提到了這種技術,但我從來沒有想過在這裏使用它。 –