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.
JavaScript
x
5
1
class Foo(Base):
2
__tablename__ = "foo"
3
user_id = Column(INTEGER, ForeignKey("users.id"), nullable=False)
4
calculated = Column(INTEGER, nullable=False, default=0, server_default=FetchedValue())
5
JavaScript
1
4
1
data = Foo(user_id=1) # even with no 'calculated' column specified, the sql query generated by SQLAlchemy includes 'calculated'
2
session.add(data)
3
await session.commit()
4
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.
JavaScript
1
9
1
from sqlalchemy import text
2
3
data = Foo(
4
user_id=1,
5
calculated=text("DEFAULT")
6
)
7
session.add(data)
8
await session.commit()
9