Skip to content
Advertisement

SQLAlchemy / mysql – How to insert data without calculated (computed) columns

I have a calculated (computed) column in a table and would like to insert rows with the calculated column not specified with SQLAlchemy. However, the SQL query for insert generated by SQLAlchemy includes the calculated column. Is there a way not to specify a column in this case?

Please refer to the following.

class Foo(Base):
    __tablename__ = "foo"
    user_id = Column(INTEGER, ForeignKey("users.id"), nullable=False)
    calculated = Column(INTEGER, nullable=False, default=0, server_default=FetchedValue())
data = Foo(user_id=1) # even with no 'calculated' column specified, the sql query generated by SQLAlchemy includes 'calculated' 
session.add(data)
await session.commit()

Advertisement

Answer

It looks like mysql accepts “DEFAULT” for a generated column.

For INSERT, REPLACE, and UPDATE, if a generated column is inserted into, replaced, or updated explicitly, the only permitted value is DEFAULT.

https://dev.mysql.com/doc/refman/5.7/en/create-table-generated-columns.html

The following code seems to work.

from sqlalchemy import text

data = Foo(
  user_id=1,
  calculated=text("DEFAULT")
)
session.add(data)
await session.commit()
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement