如果我有一个sqlalchemy对象,我试图用默认值实例化。它映射到两个表的联接,BusinessObj()有没有办法在联接不是属性或显式初始化表中字段的情况下调用TableA和TableB的初始化?
在以下示例中,field_1
应该自动填充default_field
,但根本不填充。
from pprint import pprint
from random import randrange
from sqlalchemy import MetaData, Column, Integer,String, Boolean, ForeignKey, join
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import column_property, relationship, synonym
metadata = MetaData()
Base = declarative_base()
def new_id():
return randrange(1000,9999)
class TableA(Base):
__tablename__ = 'table_a'
table_a_id = Column(Integer, primary_key=True)
field_1 = Column(Integer)
id = synonym(table_a_id)
def __init__(self, table_a_id=new_id(), field_1='default_field'):
self.table_a_id = table_a_id
self.field_1 = field_1
class TableB(Base):
__tablename__ = 'table_b'
table_b_id = Column(Integer, primary_key=True)
name = Column(String)
id = synonym(table_b_id)
def __init__(self, table_b_id=new_id(), name='default_name'):
self.table_b_id = table_b_id
self.name = name
combo = join(TableA, TableB, onclause=TableA.table_a_id == TableB.table_b_id)
class BusinessObj(Base):
__table__ = combo
id = column_property(TableA.table_a_id, TableB.table_b_id)
def __init__(self, name='frank', id=new_id()):
self.name = name
self.id = id
new_bus_obj = BusinessObj()
pprint(vars(new_bus_obj))
{'_sa_instance_state': <sqlalchemy.orm.state.InstanceState object at 0x03597750>,
'id': 7599,
'name': 'frank'}