How do I set attribute default values in sqlalchemy declarative?

前端 未结 1 1653
北海茫月
北海茫月 2020-12-17 17:01

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:

相关标签:
1条回答
  • 2020-12-17 17:37

    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
    

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

    0 讨论(0)
提交回复
热议问题