如何在 sqlalchemy 声明中设置属性默认值? [英] How do I set attribute default values in sqlalchemy declarative?

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

问题描述

在 SQLAlchemy Declarative 中,如何为列设置默认值,以便瞬态或挂起的对象实例将具有这些默认值?一个简短的例子:

In SQLAlchemy Declarative, how do I set up default values for columns, such that transient or pending object instances will have those default values? A short example:

from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class A(Base):
  __tablename__ = "A"
  id = Column(Integer, primary_key=True)
  word = Column(String, default="adefault")

a = A()
print a.word

天真地,我希望它的输出是adefault.当然,输出实际上是None.即使在添加到会话时,它也会保持None 并且仅在我提交(或刷新)会话并从数据库中重新读取实例值时才会被填充.

Naively, I would expect the output from this to be adefault. Of course, the output is actually None. Even when adding to a session, it staysNone and only gets filled when I commit (or flush) the session, and re-read the instance value from the database.

有没有办法在不将实例刷新到数据库的情况下设置属性默认值?我尝试调查 ColumnDefault 文档,似乎没有明显的方法来检查类型/python 值,以便在自定义声明性基类中手动设置它.

Is there any way to set an attribute default without flushing the instance to the database? I tried investigating the ColumnDefault documentation, and there doesn't seem to be an obvious way to inspect the type/python value, so as to manually set it in a custom declarative baseclass.

推荐答案

向类添加构造函数并在那里设置默认值.从数据库加载行时,构造函数不会运行,因此可以执行此操作.

Add a constructor to your class and set the default value there. The constructor doesn't run when the rows are loaded from the database so it is fine to do this.

class A(Base):
    __tablename__ = "A"
    id = Column(Integer, primary_key=True)
    word = Column(String)

    def __init__(self):
        self.word = "adefault"

a = A()
print a.word

SA 文档.

There are examples of using __init__ in similar ways in the SA Docs.

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

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