0

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 \"==\"?"

1 Answer 1

1

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

insert(tablename).values(**{field_id: 'foo'})
Sign up to request clarification or add additional context in comments.

1 Comment

Great thank-you, that worked a charm, I was being a bit dumb.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.