Retreive max/min possible values for an Integer column [duplicate] - python

I have this query:
mps = (
session.query(mps) .filter_by(idc = int(c.idc))
.filter_by(idmp = int(m.idmp))
.group_by(func.day(mps.tschecked))
).all()
My problem is, that I don't know how to extract (with sqlalchemy) the max/min/avg value from a table...
I find this: Database-Independent MAX() Function in SQLAlchemy
But I don't know where to use this func.max/min/avg...
Can someone tell me how to do this? Can you give me an example?

The following functions are available with from sqlalchemy import func:
func.min
func.max
func.avg
Documentation is available here.
You can use them i.e. in the query() method.
Example:
session.query(self.stats.c.ID, func.max(self.stats.c.STA_DATE))
(just like you use aggregate functions in plain SQL)

Or just use an order_by() and select the first or last element. . .

Related

What is the equivalent of python 'in' but for sqlalchemy

I have a dictionary that is being used to query the database for a match. I have one single query line that isn't working for me. If i have a list like this:
user['names']= [Alice, Bob, John]
Since this is a list I tried to use something like this:
q.filter(UserTable.firstname in user['firstnames'])
But for whatever reason this doesn't work. However, I know that Bob is in the database. When I manually pull down all the queries I can see the name is there in one of the rows. If I do this instead:
q.filter(UserTable.firstname == user['firstnames'][1]) #Only does Bob
It works. And when I pull all the queries manually, convert each row to a dictionary, and then do a
row[#row_that_matches].firstname in user['names']
that also works. But for some reason using the "in" keyword in sqlalchemy doesn't work as expected. Does anyone know an alternative that can make an sqlalchemy query for something in a list of values?
Use the in_() column method to test a column against a sequence:
q.filter(UserTable.firstname.in_(user['firstnames'])
See the Common Filter Operations section of the Object Relational tutorial:
IN:
query.filter(User.name.in_(['ed', 'wendy', 'jack']))
# works with query objects too:
query.filter(User.name.in_(
session.query(User.name).filter(User.name.like('%ed%'))
))

SqlAlchemy Postgres JSON how to filter with question mark operator?

I'm struggling to convert this to an ORM filter query:
select count(*) from issues WHERE pending_notifications ? 'flooby';
pending_notifications is a JSONB field containing a simple JSON array.
I'm not sure how to structure the filter using the question mark operator
I believe a Postgres ARRAY would work like this:
query.filter(pending_notifications.any('flooby'))
But I'm using JSONB and the filter syntax is not the same.
Any suggestions
You can use the .op() method to use any verbatim operator:
query.filter(pending_notifications.op("?")("flooby"))
Given that you're using JSONB as column data type, use the has_key() method:
query.filter(pending_notifications.has_key('flooby'))
which maps to the ? operator. The method name is misleading in this context, but PostgreSQL documentation for jsonb operators describes ? thusly:
Does the string exist as a top-level key within the JSON value?
and so has_key() is somewhat aptly named.
An example:
In [21]: t = Table('t', metadata, Column('json', postgresql.JSONB))
In [28]: print(t.c.json.has_key('test'))
t.json ? :json_1
I can use raw sql in filter
from sqlalchemy import text
db.session.query(Issue).filter(text("pending_notifications ? 'flooby'")

How to replace columns in sqlalchemy query

I have the query:
q = Session.query(func.array_agg(Order.col))
The compiled query will be:
SELECT array_agg(order.col) FROM orders
I want dynamically replace the existing column. After replacing query have to be:
SELECT group_concat(orders.col) FROM orders
I have to use Session and model. I don't have to use SQLAlchemy core. I don't have to use subqueries. And, of course, there can be some other columns, but I need to replace only one. I tried to replace objects in column_descriptions property, I tried to use q.selectable.replace (or something like this, sorry, but I don't remember right names) and I didn't get right result.
The right method:
q = Session.query(func.array_agg(Order.col))
q.with_entities(func.group_concat(Order.col))
SELECT group_concat(orders.col) FROM orders

How to get peewee result length

I use peewee orm in python.
I have a query that :
userOrganizations = (UserOrganization
.select(UserOrganization,Organization)
.join(Organization)
.where(UserOrganization.user==user.user_id)
.aggregate_rows()
)
I want to get length of userOrganizations variable. Is there any method like userOrganizations.length() ?
According to the peewee documentation you can use the count() function, i.e.:
userOrganizations.count()
If you're worried about maybe running extra DB queries, you can convert your result to a list and get the length, like:
len(list(userOrganizations))
Source for second technique: this question.

sqlalchemy: get max/min/avg values from a table

I have this query:
mps = (
session.query(mps) .filter_by(idc = int(c.idc))
.filter_by(idmp = int(m.idmp))
.group_by(func.day(mps.tschecked))
).all()
My problem is, that I don't know how to extract (with sqlalchemy) the max/min/avg value from a table...
I find this: Database-Independent MAX() Function in SQLAlchemy
But I don't know where to use this func.max/min/avg...
Can someone tell me how to do this? Can you give me an example?
The following functions are available with from sqlalchemy import func:
func.min
func.max
func.avg
Documentation is available here.
You can use them i.e. in the query() method.
Example:
session.query(self.stats.c.ID, func.max(self.stats.c.STA_DATE))
(just like you use aggregate functions in plain SQL)
Or just use an order_by() and select the first or last element. . .

Categories

Resources