I would like to set a column default value that is based off of another table in my SQLAlchemy model.
我想设置一个基于SQLAlchemy模型中另一个表的列默认值。
Currently I have this:
目前我有这个:
Column('version', Integer, default=1)
What I need is (roughly) this:
我需要的是(大致)这个:
Column('version', Integer, default="SELECT MAX(1, MAX(old_versions)) FROM version_table")
How can I implement this in SQLAlchemy?
我如何在SQLAlchemy中实现它?
2 个解决方案
#1
25
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.
标量,Python可调用或ClauseElement,表示此列的默认值,如果在插入的VALUES子句中未指定此列,则将在插入时调用。
You may look into using a simple function, or you may just be able to use a select()
object.
您可以考虑使用一个简单的函数,或者您可以使用select()对象。
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))]))
#2
0
You want server_default
你想要server_default
Column('version', Integer, server_default="SELECT MAX(1, MAX(old_versions)) FROM version_table")
#1
25
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.
标量,Python可调用或ClauseElement,表示此列的默认值,如果在插入的VALUES子句中未指定此列,则将在插入时调用。
You may look into using a simple function, or you may just be able to use a select()
object.
您可以考虑使用一个简单的函数,或者您可以使用select()对象。
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))]))
#2
0
You want server_default
你想要server_default
Column('version', Integer, server_default="SELECT MAX(1, MAX(old_versions)) FROM version_table")