Search code examples
sqlalchemypython-asynciostarlette

How to get the LAST INSERT ID when using python-asyncio databases


I'm trying to persist an object in the database using the following stack: Starlette, SQLArchemy and Databases.

How can I get the LAST INSERT ID?

class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    username = Column(String)
async def create_user(request: Request) -> JSONResponse:
    data = await request.json()
    query = User.__table__.insert().values(name=data["username"])
    await database.execute(query)

    # I need the LAST INSERT ID here

Solution

  • I was not expecting the solution to be that simple. I couldn't find it in the documentation.

    It seems that the result of the query will return the LAST INSERT ID if there is one:

        last_insert_id = await database.execute(query)