Sqlalchemy RETURNING scalar

Viewed 276

i was messing around with the sqlalchemy return clause, consider the following code

stmt = insert(A).values({"data": "data", "id":2}).returning(A)
result = await session.execute(stmt)
print(type(result.scalar()))

the output just prints a integer

but if I use a select statement instead of return it gives the mapped row object?

stmt = select(A).where(A.id == 2)
result = await session.execute(stmt)
print(type(result.scalar()))

why does this happen?

1 Answers

The first execution returns the tuple (2, 'data'), the second (<__main__.A object at 0x7f32b9fbefe0>,). However calling result.scalar will

Fetch the first column of the first row, and close the result set.

Thus you get 2 for the first execution, but a model instance for the second.

Related