Sergey Khaylov
Sergey Khaylov

Reputation: 183

sqlalchemy select to_date

Connected to an Oracle database, I need to run the following query:

SELECT
    ad_campaign_id as campaign_id,
    TO_DATE("DAY", 'YYYY-MM-DD') as DAY,
    NVL(spent, 0) as spent,
    impressions,
    clicks 
FROM sometable

How can I do that with SQLAlchemy? How I can send paramaters to the func.to_date function?

Upvotes: 1

Views: 2992

Answers (2)

dmvianna
dmvianna

Reputation: 15718

SQLAlchemy's func will accept any Oracle function as an attribute.

from sqlalchemy import func

campaign_id = sometable.c.ad_campaign_id
day = func.to_date(sometable.c.day, 'YYYY-MM-DD') # Is this what you need?
spent = func.nvl(sometable.c.spent, 0)
clicks = sometable.c.clicks
cols = [campaign_id, day, spent, clicks]

# Feel free to skip, this is just so you get the labels you want
labels = "campaign_id day spent clicks".split()
col_label = zip(cols, labels)
labelled = [c.label(l) for (c,l) in col_label]

q = session.query(*labelled) # or use *cols if you don't care about labels
q.all()

Upvotes: 4

Sheena
Sheena

Reputation: 16212

Here's how you execute arbitrary queries:

engine.execute(query_string)

setting up the engine is another story. It's pretty well documented though.

If you are asking how to do this using some model that's a different story again...

So that's the first part of your question answered (possibly). But what do you mean by the func.to_date function? Please clarify

Upvotes: 0

Related Questions