Set default values before commit in sqlalchemy.orm



A little special use case

Create an ORM in class declaration format from declarative_base in sqlalchemy.orm.

I want to create ʻUser` class as follows and set the initial value of num to 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)

Since None and 1 cannot be added, an error will occur if this is left as it is. If you look there, you will find default, server_default keyword parameter.

default is the value used when committing to table, server_default is the initial value inside CREATE TABLE.

When you want to use it before commit ...? It took longer than necessary to find it. The conclusion is simple and you should use __init__ normally.

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)

The reference also says that you can use __init__. http://docs.sqlalchemy.org/en/latest/orm/constructors.html#mapping-constructors

Recommended Posts

Set default values before commit in sqlalchemy.orm
Get environment variables in Python, otherwise set default values
To set default encoding to utf-8 in python
Set spinning_friction in pybullet
Set ulimit in supervisor
Swapping values in Python