在 sqlalchemy 中设置默认值 [英] Setting a default value in sqlalchemy

查看:84
本文介绍了在 sqlalchemy 中设置默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想设置一个基于 SQLAlchemy 模型中另一个表的列默认值.

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

目前我有这个:

Column('version', Integer, default=1)

我需要的是(大致)这个:

What I need is (roughly) this:

Column('version', Integer, default="SELECT MAX(1, MAX(old_versions)) FROM version_table")

如何在 SQLAlchemy 中实现这一点?

How can I implement this in SQLAlchemy?

推荐答案

documentationdefault 提供了以下可能性:

The documentation gives the following possibilities for default:

表示默认值的标量、Python 可调用或 ClauseElement此列的值,如果此值将在插入时调用否则不会在插入的 VALUES 子句中指定列.

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.

您可能会考虑使用一个简单的函数,或者您可能只能使用 select() 对象.

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))]))

这篇关于在 sqlalchemy 中设置默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆