SQLAlchemy: Override relationship-defined order_by in a query

2024/10/15 2:33:16

So, I have a model that is something like:

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)")@propertydef first_item(self):# the problem is here:return self.data.order_by(asc("timestamp")).first()@propertydef 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 with the first_item method there: when it is defined as above, the 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, the order_by specified in the query is being appended to the one specified in the relationship definition, instead of replacing it; is there a way for a query to override the original order_by? I know I could specify a separate query directly on the FooData class, but I would like to avoid that if possible.

Answer

According to documentation:

All existing ORDER BY settings can be suppressed by passing None - this will suppress any ORDER BY configured on mappers as well.

So the simple solution is to reset ORDER BY clause and then apply the one you need. Like:

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

In case you don't want to reset whole ORDER BY clause, but only want to override one column order, AFAIK there is no built-in way for it.

https://en.xdnf.cn/q/69338.html

Related Q&A

Toplevel in Tkinter: Prevent Two Windows from Opening

Say I have some simple code, like this:from Tkinter import * root = Tk() app = Toplevel(root) app.mainloop()This opens two windows: the Toplevel(root) window and the Tk() window. Is it possible to avoi…

Specify File path in tkinter File dialog

I have a file dialog to open a file, however, the file that I want to open is in a different directory than the program I wrote. The file dialog opens to the directory where I am. Is there a way to s…

Why does scipy linear interpolation run faster than nearest neighbor interpolation?

Ive written a routine that interpolates point data onto a regular grid. However, I find that scipys implementation of nearest neighbor interpolation performs almost twice as slow as the radial basis f…

How do I create a 404 page?

My application catches all url requests with an @app.route, but occasionally I bump into a bad url for which I have no matching jinja file (bu it does match an existing @app.route). So I want to redire…

Injecting pre-trained word2vec vectors into TensorFlow seq2seq

I was trying to inject pretrained word2vec vectors into existing tensorflow seq2seq model.Following this answer, I produced the following code. But it doesnt seem to improve performance as it should, a…

MySQL Stored Procedures, Pandas, and Use multi=True when executing multiple statements

Note - as MaxU suggested below, the problem is specific to mysql.connector and does not occur if you use pymysql. Hope this saves someone else some headachesUsing Python, Pandas, and mySQL and cannot…

How can I change the font size in GTK?

Is there an easy way to change the font size of text elements in GTK? Right now the best I can do is do set_markup on a label, with something silly like:lbl.set_markup("<span font_desc=Tahoma …

How to read BigQuery table using python pipeline code in GCP Dataflow

Could someone please share syntax to read/write bigquery table in a pipeline written in python for GCP Dataflow

How can I wrap a python function in a way that works with with inspect.signature?

Some uncontroversial background experimentation up front: import inspectdef func(foo, bar):passprint(inspect.signature(func)) # Prints "(foo, bar)" like youd expectdef decorator(fn):def _wra…

Python OpenCV Error: TypeError: Image data cannot be converted to float

So I am trying to create a Python Program to detect similar details in two images using Pythons OpenCV. I have the two images and they are in my current directory, and they exist (see the code in line…