Paul Bradbury
Paul Bradbury

Reputation: 145

Inserting into dynamic column name using SQLAlchemy

How do you insert values into a dynamic column name in SQLAlchemy? I am trying to insert values into a table using dynamic column names that are passed into the function.

I have tried:

        field_id = "column_name"

        query = (
            insert(
                TableName
            )
            .values(
                getattr(TableName.c, field_id)=value
            )
        )

But that tells me I can't assign a value to an expression

SyntaxError: expression cannot contain assignment, perhaps you meant \"==\"?"

Upvotes: 0

Views: 465

Answers (1)

snakecharmerb
snakecharmerb

Reputation: 55600

You need to create a dictionary, and then unpack it, like this:

insert(tablename).values(**{field_id: 'foo'})

Upvotes: 1

Related Questions