为什么在提交对象之前SQLAlchemy默认列值不可用? [英] Why isn't SQLAlchemy default column value available before object is committed?

查看:70
本文介绍了为什么在提交对象之前SQLAlchemy默认列值不可用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我发现SQLAlchemy的Column默认值不起作用,正如我期望的那样:

Recently I figured out that SQLAlchemy's Column default doesn't work as I expect it to:

>>> Base = declarative_base()
>>> class TestModel(Base):
    ...     __tablename__ = 'tmodel'
...     id = sa.Column(sa.Integer, primary_key=True)
...     foo = sa.Column(sa.Integer, default=0)
...    
>>> tmodel_instance = TestModel()
>>> print tmodel_instance.foo
None
>>> session.add(tmodel_instance)
>>> print tmodel_instance.foo
None
>>> session.commit()
>>> print tmodel_instance.foo
0

我要 tmodel_instance.foo 在对象实例化后立即等于 0 ,但似乎仅在执行 INSERT 命令,这确实使我感到困惑。为什么会比 server_default 更喜欢 default ?以及如何实现我想要的?我是否应该在 __ init __ 中指定所有默认参数?似乎是代码重复:要更改默认值,我必须将其更改两次并保持这些值相等-有什么方法可以避免这种情况?

I want tmodel_instance.foo to equal 0 right after object instantiation, but it seems that the default value is only used when executing INSERT command, and it really confuses me. Why would one prefer the default over server_default? And how do I achieve what I want? Am I supposed to specify all default arguments in __init__? That seems to be code duplication: to change the default value I have to change it twice and maintain those values equality -- is there some way to avoid that?

推荐答案

您可以使用 sqlalchemy_utils 中的 force_instant_defaults 侦听器来更改此行为:

You can use force_instant_defaults listener from sqlalchemy_utils to change this behavior:

from sqlalchemy_utils import force_instant_defaults

force_instant_defaults()

class TestModel(Base):
    __tablename__ = 'tmodel'
    id = sa.Column(sa.Integer, primary_key=True)
    foo = sa.Column(sa.Integer, default=0)

model = TestModel()
assert model.foo == 0

这篇关于为什么在提交对象之前SQLAlchemy默认列值不可用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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