'Sqlalchemy. Get inserted default values

Preface: My task is storing files on a disk, the part of a file name is a timestamp. Path to these files is storing in DB. Multiple files may have a single owner entity (one message can contain multiple attachments). To make things easier I want to have the same timestamp for file paths in DB (it's set to default now()) and files on the disk.

Question: So after insertion, I need to get back default inserted values (in most cases primary_key_id and created_datetime).

I tried:

db_session  # Just for clarity
<sqlalchemy.orm.session.AsyncSession object at 0x7f836691db20>

str(statement)  # Just for clarity. Don't know how to get back the original python (not an SQL) statement
'INSERT INTO users (phone_number, login, full_name, hashed_password, role) VALUES (:phone_number, :login, :full_name, :hashed_password, :role)'

query_result = await db_session.execute(statement=statement)

query_result.returned_defaults_rows  # Primary_key, but no datetime
[(243,)]

query_result.returned_defaults  # Primary_key, but no datetime
(243,)

query_result.fetchall()
[]

My tables:

Base = declarative_base()  # Main class of ORM; Put in config by suggestion https://t.me/ru_python/1450665

claims = Table(  # TODO set constraints for status
    "claims",
    Base.metadata,
    Column("id", Integer, primary_key=True),

My queries

async def create_item(statement: Insert, db_session: AsyncSession, detail: str = '') -> dict:
    try:  # return default created values
        statement = statement.returning(statement.table.c.id, statement.table.c.created_datetime)
        return (await db_session.execute(statement=statement)).fetchone()._asdict()
    except sqlalchemy.exc.IntegrityError as error:
        # if psycopg2_errors.lookup(code=error.orig.pgcode) in (psycopg2_errors.UniqueViolation, psycopg2_errors.lookup):
        detail = error.orig.args[0].split('Key ')[-1].replace('(', '').replace(')', '').replace('"', '')
        raise HTTPException(status_code=422, detail=detail)

P.S. Sqlalchemy v 1.4



Solution 1:[1]

I was able to do this with session.bulk_save_objects(objects, return_defaults=True)

Docs on this method are here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nick Tallant