Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set attribute default values in 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

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.

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.

like image 436
misnomer Avatar asked Nov 14 '12 18:11

misnomer


1 Answers

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.

like image 195
Tony Gibbs Avatar answered Oct 08 '22 08:10

Tony Gibbs