Setting a default value in sqlalchemy

前端 未结 2 409
野的像风
野的像风 2020-12-16 09:15

I would like to set a column default value that is based on another table in my SQLAlchemy model.

Currently I have this:

Column(\'version\', Integer,         


        
相关标签:
2条回答
  • 2020-12-16 09:28

    The documentation gives the following possibilities for default:

    A scalar, Python callable, or ClauseElement representing the default value for this column, which will be invoked upon insert if this column is otherwise not specified in the VALUES clause of the insert.

    You may look into using a simple function, or you may just be able to use a select() object.

    In your case, maybe something along the lines of:

    from sqlalchemy.sql import select, func
    ...
    Column('version', Integer, default=select([func.max(1,
        func.max(version_table.c.old_versions))]))
    
    0 讨论(0)
  • 2020-12-16 09:35

    You want server_default

    Column('version', Integer, server_default="SELECT MAX(1, MAX(old_versions)) FROM version_table")
    
    0 讨论(0)
提交回复
热议问题