Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a label in a having clause in sqlachemy

I'm trying to use a label in a having clause with sqlalchemy, but I'm having problems getting it working. I'm trying something like this:

qry = db.session.query(
         Foo.id,
         Foo.name,
         (Foo.max_stuff - func.sum(Bar.stuff)).label('rstuff')
).join(Bar) \
 .group_by(Foo.id) \
 .having('rstuff' >= "some_data_passed_in_by_customer")

for res in qry.all(): 
    print res

But get the error:

sqlalchemy.exc.ArgumentError: having() argument must be of type sqlalchemy.sql.ClauseElement or string

If I try changing the having statement to:

.having('rstuff >= "some_data_passed_in_by_customer"')

Then it seems to work alright, but I'm guess that would lead to a sql injection vulnerability. I could do this via raw sql, but I would like to avoid that if I could. Any ideas?

like image 443
vimalloc Avatar asked Oct 16 '25 18:10

vimalloc


1 Answers

Try any of the two versions below (not sure the second one works on MySQL though):

rstuff = (Foo.max_stuff - db.func.sum(Bar.stuff))
qry = (
    db.session.query(
        Foo.id,
        Foo.name,
        rstuff.label('rstuff')
    )
    .join(Bar)
    .group_by(Foo.id)

    # version-1: probably universal, but repeats the expression
    .having(rstuff >= 3)
    # version-2: might depend on the RMDBS engine
    # .having(db.literal_column('rstuff') >= 3)
)
like image 163
van Avatar answered Oct 19 '25 08:10

van



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!