为什么在提交对象之前

为什么在提交对象之前

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

问题描述

最近我发现 SQLAlchemy 的 Column 默认设置并没有像我预期的那样工作:

>>>Base = declarative_base()>>>类测试模型(基础):... __tablename__ = 'tmodel'... id = sa.Column(sa.Integer, primary_key=True)... foo = sa.Column(sa.Integer, default=0)...>>>tmodel_instance = 测试模型()>>>打印 tmodel_instance.foo没有任何>>>session.add(tmodel_instance)>>>打印 tmodel_instance.foo没有任何>>>session.commit()>>>打印 tmodel_instance.foo0

我希望 tmodel_instance.foo 在对象实例化后立即等于 0,但似乎默认值仅在执行 INSERT 时使用命令,它真的让我感到困惑.为什么人们更喜欢 default 而不是 server_default?我如何实现我想要的?我应该在 __init__ 中指定所有默认参数吗?这似乎是代码重复:要更改默认值,我必须更改它两次并保持这些值相等——有没有办法避免这种情况?

解决方案

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

from sqlalchemy_utils import force_instant_defaultsforce_instant_defaults()类测试模型(基础):__tablename__ = 'tmodel'id = sa.Column(sa.Integer, primary_key=True)foo = sa.Column(sa.Integer, default=0)模型 = 测试模型()断言 model.foo == 0

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

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?

解决方案

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 默认列值不可用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 09:55