Skip to content

Tag: sqlalchemy

“set session” in a SQLAlchemy session object

I’m using SQLAlchemy for a project, and need to be able to specify a session variable/setting for one specific call for performance reasons: I can of course do this in MySQL directly (on the shell), but how do I set this session variable in a SQLAlchemy session? Answer Use a session event to execute an …

Altering an Enum field using Alembic

How can I add an element to an Enum field in an alembic migration when using a version of PostgreSQL older than 9.1 (which adds the ALTER TYPE for enums)? This SO question explains the direct process, but I’m not quite sure how best to translate that using alembic. This is what I have: The above unfortu…

SQLAlchemy ORM select multiple entities from subquery

I need to query multiple entities, something like session.query(Entity1, Entity2), only from a subquery rather than directly from the tables. The docs have something about selecting one entity from a subquery but I can’t find how to select more than one, either in the docs or by experimentation. My use …

How to get month and year from Date field in sqlalchemy?

The result should be Date object Since the day cannot be ‘removed’, set it to say, 1st day of the month. Leaving only Month, Year Answer You can use following constructs to filter the Date column using either year or month: And group_by is also possible: Now I haven’t tested it, but I assume…

Setting a default value in sqlalchemy

I would like to set a column default value that is based on another table in my SQLAlchemy model. Currently I have this: What I need is (roughly) this: How can I implement this in SQLAlchemy? Answer The documentation gives the following possibilities for default: A scalar, Python callable, or ClauseElement re…