Does SQLAlchemy have an equivalent of Django’s get_or_create?

Following the solution of @WoLpH, this is the code that worked for me (simple version): def get_or_create(session, model, **kwargs): instance = session.query(model).filter_by(**kwargs).first() if instance: return instance else: instance = model(**kwargs) session.add(instance) session.commit() return instance With this, I’m able to get_or_create any object of my model. Suppose my model object is : class Country(Base): __tablename__ = … Read more

How to update SQLAlchemy row entry?

There are several ways to UPDATE using sqlalchemy 1) user.no_of_logins += 1 session.commit() 2) session.query(User).\ filter(User.username == form.username.data).\ update({‘no_of_logins’: User.no_of_logins + 1}) session.commit() 3) conn = engine.connect() stmt = User.update().\ values(no_of_logins=User.no_of_logins + 1).\ where(User.username == form.username.data) conn.execute(stmt) 4) setattr(user, ‘no_of_logins’, user.no_of_logins + 1) session.commit()

sqlalchemy unique across multiple columns

Extract from the documentation of the Column: unique – When True, indicates that this column contains a unique constraint, or if index is True as well, indicates that the Index should be created with the unique flag. To specify multiple columns in the constraint/index or to specify an explicit name, use the UniqueConstraint or Index … Read more

SQLAlchemy: print the actual query

In the vast majority of cases, the “stringification” of a SQLAlchemy statement or query is as simple as: print(str(statement)) This applies both to an ORM Query as well as any select() or other statement. Note: the following detailed answer is being maintained on the sqlalchemy documentation. To get the statement as compiled to a specific … Read more

SQLAlchemy default DateTime

Calculate timestamps within your DB, not your client For sanity, you probably want to have all datetimes calculated by your DB server, rather than the application server. Calculating the timestamp in the application can lead to problems because network latency is variable, clients experience slightly different clock drift, and different programming languages occasionally calculate time … Read more

SQLAlchemy IN clause

How about session.query(MyUserClass).filter(MyUserClass.id.in_((123,456))).all() edit: Without the ORM, it would be session.execute( select( [MyUserTable.c.id, MyUserTable.c.name], MyUserTable.c.id.in_((123, 456)) ) ).fetchall() select() takes two parameters, the first one is a list of fields to retrieve, the second one is the where condition. You can access all fields on a table object via the c (or columns) property.