SQLAlchemy: Override associated with the definition of "order_by" in the query

So, I have a model that looks something like this:

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)

So, the problem is the method first_item: when it is defined as above, SQL looks like this:

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
--                                                                 ^^^^^^^^^^^^^^^^^^^^^^

Obviously, what order_byis specified in the request is added to the one indicated in the definition of the relationship, instead of replacing it; is there any way for the request to override the original order_by? I know that I can specify a separate request directly in the class FooData, but I would like to avoid this if possible.

+4
source share
1 answer

According to the documentation :

ORDER BY None - ORDER BY, mappers.

, reset ORDER BY, , . :

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

reset whole ORDER BY, , AFAIK .

+4

Source: https://habr.com/ru/post/1609352/


All Articles