How do I create as assoc record with SQLAlchemy in Pylons?
I've got a User
model and a Ledger
model with a many-to-many relationship. SQLAlchemy has created my database tables correctly, so I'm pretty sure it's got the right mappings. I can create a new record in each table, but I can't figure out how to associate them. How do I do it?
My table definitions:
user_table = sa.Table('user', meta.metadata,
sa.Column('id', types.Integer,
sa.Sequence('user_seq_id', optional=True), primary_key=True),
sa.Column('username', types.Unicode(255), nullable=False, unique=True),
sa.Column('password', types.Unicode(255), nullable=False),
sa.Column('salt', types.Unicode(255), nullable=False)
)
userledger_table = sa.Table('userledger', meta.metadata,
sa.Column('id', types.Integer,
sa.Sequence('user_seq_id', optional=True), primary_key=True),
sa.Column('user_id', types.Integer(), sa.ForeignKey('user.id')),
sa.Column('ledger_id', types.Integer(), sa.ForeignKey('ledger.id')),
)
ledger_table = sa.Table('ledger', meta.metadata,
sa.Column('id', types.Integer,
sa.Sequence('ledger_seq_id', optional=True), primary_key=True),
sa.Column('name', types.Unicode(255), nullable=False),
)
Mappings:
orm.mapper(User, user_table);
orm.mapper(Ledger, ledger_table, properties={
'users':orm.relation(User, seconda开发者_运维技巧ry=userledger_table)
})
I found my answer in this tutorial.
ledger = model.Ledger()
ledger.name = name
ledger.users.append(user)
meta.Session.add(ledger)
meta.Session.commit()
精彩评论