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()
3
Answers
It looks like mysql accepts "DEFAULT" for a generated column.
https://dev.mysql.com/doc/refman/5.7/en/create-table-generated-columns.html
The following code seems to work.
You can use excluded_columns attribute on your Foo class, please try the below and see if that works
The
calculated
column is present in the generatedINSERT
statement because you havedefault=0
in the column definition. If you removedefault=0
it will not be passed, however as the column is not nullable the value must be computed immediately on the server.This script shows how it would work with a trigger doing the computation on the server side.
Generating this
INSERT
statement: