根据Sqlalchemy 创建者的建议,我正在尝试使用 SQL Expression Language编写我的初始批量插入数据。详情请参阅。
本教程涵盖了我认为是用户和地址之间一对多关系的示例。他们使用 executemany() 方法创建关系:
>>> conn.execute(addresses.insert(), [
... {'user_id': 1, 'email_address' : 'jack@yahoo.com'},
... {'user_id': 1, 'email_address' : 'jack@msn.com'},
... {'user_id': 2, 'email_address' : 'www@www.org'},
... {'user_id': 2, 'email_address' : 'wendy@aol.com'},
... ])
INSERT INTO addresses (user_id, email_address) VALUES (?, ?)
((1, 'jack@yahoo.com'), (1, 'jack@msn.com'), (2, 'www@www.org'), (2, 'wendy@aol.com'))
COMMIT
<sqlalchemy.engine.ResultProxy object at 0x...>
在我的设计中,我有几个多对多的关系。一种介于用户和组织之间。注意我正在使用Flask-Sqlalchemy。
# assuming a relationship like:
# organizations = db.Table('organizations',
# db.Column('organization_id', db.Integer, db.ForeignKey('organization.id')),
# db.Column('user_id', db.Integer, db.ForeignKey('user.id')))
# class User(db.Model):
# ...
# organizations = db.relationship('Organization', secondary=organizations,
# backref=db.backref('users', lazy='dynamic'))
# class Organization(db.Model):
# ...
def db_reset():
# lets reset it
db.drop_all()
db.create_all()
# establish our connection
engine = create_engine(SQLALCHEMY_DATABASE_URI)
conn = engine.connect()
# load in our users
user_insert = User.__table__insert()
for user in users: # users is a list of named tuples
conn.execute(user_insert, name=user.name, role=user.role,
organizations= [orgA,orgB,...etc] # how do i do this?
所以我的问题包含在我的代码和标题中。使用 SQL 表达式语言如何建立多对多关系?