http://www.ergo.io/blog/sqlalchemy-relationships-from-beginner-to-advanced
class Cabinet(db.Model):
__tablename__ = 'cabinet'
uuid = db.Column(db.String(40), primary_key=True, nullable=True, default=str(uuid.uuid4()))
id = db.Column(db.String(20))
description = db.Column(db.Text)
racks = db.relationship('Rack', backref='cabinet')
class Rack(db.Model):
__tablename__ = 'rack'
uuid = db.Column(db.String(40), primary_key=True, nullable=True, default=str(uuid.uuid4()))
id = db.Column(db.String(20))
cabinet_id = db.Column(db.String(40), db.ForeignKey('cabinet.uuid'))
方法1
racks = [ Rack(uuid=uuid.uuid4(), id=i for i in xrange(1,43) ]
cabinet = Cabinet(id='bj-01', description='bj-01', racks=racks)
# 前一个racks是到Rack的关联对象,后一个racks是一个Rack对象数组
db.session.add(cabinet)
db.session.commit()
方法2
cabinet = Cabinet(id='bj-01', description='bj-01')
db.session.add(cabinet)
for i in xrange(42):
rack = Rack(uuid=str(uuid.uuid4()), id=i, cabinet=cabinet)
#cabinet是反向引用
db.session.add(rack)
db.session.commit()