相关疑难解决方法(0)

SQLAlchemy:在查询中覆盖关系定义的"order_by"

所以,我有一个类似的模型:

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)
Run Code Online (Sandbox Code Playgroud)

所以,问题在于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
--                                                                 ^^^^^^^^^^^^^^^^^^^^^^ …
Run Code Online (Sandbox Code Playgroud)

python sqlalchemy

5
推荐指数
1
解决办法
1174
查看次数

标签 统计

python ×1

sqlalchemy ×1