9
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

sqlalchemy.orm で commit 前にデフォルト値を設定する

Last updated at Posted at 2016-05-24

<<少し特殊なユースケースです>>

sqlalchemy.orm で declarative_base からクラス宣言形式で ORM を作る。

次のように User class を作って、num の初期値を 0 にしたい。

from sqlalchemy import create_engine
from sqlalchemy import Column, Integer, text
from sqlalchemy.ext.declarative import declarative_base

engine = create_engine("sqlite:///:memory:", echo=True)
Base = declarative_base()

class User(Base):
	__tablename__="users"
	id = Column(Integer, primary_key=True)
	num = Column(Integer)

Base.metadata.create_all(engine)

u = User()
print(u.id, u.num+1)

None と 1 は足せないので、このままだとエラーになる。そこで調べてみると default, server_default keyword parameter が見つかる。

default は table に commit するときに使われる値、server_defaultCREATE TABLE の中に入る初期値。

commit 前に使いたいときは…?というのを探すのに必要以上に時間がかかってしまった。結論は簡単で普通に __init__ を使うべし。

from sqlalchemy import create_engine
from sqlalchemy import Column, Integer, text
from sqlalchemy.ext.declarative import declarative_base

engine = create_engine("sqlite:///:memory:", echo=True)
Base = declarative_base()

class User(Base):
	def __init__(self, *args, **kwargs):
		super(Base, self).__init__(*args, **kwargs)
		self.num = 0
	
	__tablename__="users"
	id = Column(Integer, primary_key=True)
	num = Column(Integer, server_default=text("0"))

Base.metadata.create_all(engine)

u = User()
print(u.id, u.num+1)

リファレンスにも __init__ 使えと書いてある。http://docs.sqlalchemy.org/en/latest/orm/constructors.html#mapping-constructors

9
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?