在 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__init__ 的示例映射"rel="noreferrer">SA 文档.
There are examples of using __init__ in similar ways in the SA Docs.
更多推荐
如何在 sqlalchemy 声明中设置属性默认值?
发布评论