Look at this query:
select 'DEFAULT_STRING' as category from foo
Here, we don't really have the column category in the table, but we just use a string literal to represent this column value in all rows returned by the query. In place of a string literal, we could have any valid SQL expression above. Is there some way to have this query in the django ORM?
A handy way of doing this is to annotate with RawSQL query expression.
from django.db.models.expressions import RawSQL
qset = Foo.objects.annotate(category=RawSQL("select 'DEFAULT_CATEGORY'", ()))
Please let me know in the answers if there are better ways of doing this.
Related
I using flask-appbuilder with SQLAlchemy models, I find all their datamodel filter using "and" relationship.
I mean when the flask query something, it do:
self.datamodel.filter_by(id='abt').filter_by(testz_pro='mytest')
But I want to using 'or' relationship:
the sql like:
select * from number where id='1232' or id ='34343'
So, I have to change the 'or' relationship to 'and'
So, My sql is like:
select * from number where not (id<>'1232' and id<>'34343')
I just do not know for SQLAlchemy query how to expressure 'not'.
Can you give me example?
You need to use the filter method for this, as it is not possible to negate filter_by's keyword arguments.
from sqlalchemy import and_, not_
session.query(MyModel).filter(not_(and_(MyModel.id='abt', MyModel.testz_pro='mytest')))
How in SQLAlchemy ORM to make analogue of the following raw sql?
SELECT "http://example.com/page/"||table.pagename as pageUrl
Need get value from table, modify using ORM/Python (here just a string concatenation), and output in result of the SQLAlchemy query as additional field.
The SQLAlchemy string types have operator overloads that allow you to treat them like you'd treat Python strings in this case (string concatenation), but produce SQL expressions:
session.query(
Table,
("http://example.com/page/" + Table.pagename).label("pageUrl"))
You can read more about SQLAlchemy's operator paradigm here: http://docs.sqlalchemy.org/en/latest/core/tutorial.html#operators
This can make via select, but there is almost no ORM:
from sqlalchemy.sql import select, text
q = select([text('"http://example.com/page/"||pagename as pageUrl')]).select_from(Table)
session.execute(q).fetchall()
Results will a list of objects in the RowProxy class.
For me seems that the solve via session.query (the answer above) is more convenient. It is short, and there results in result class that can be easy converting to dict.
I'm trying to use both .contains and .ilike to filter a query from a string value.
For example the query should look something like this:
model.query.filter(model.column.contains.ilike("string").all()
Currently querying by .contains returns case sensitive results. And querying by ilike returns case unsensitive results, but the characters must match which is far too specific a query. I want potential results to appear to the user as they do with a .contains query.
foo = model.query.filter(model.column.ilike("%"+ string_variable +"%")).all()
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'")
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