使用Sqlalchemy ORM插入,更新或删除关系表

时间:2015-12-06 17:33:42

标签: python sqlalchemy

我有三张这样的表,

class User(Base):
    __tablename__ = 'user'
    id = Column(Integer, primary_key=True)
    name = Column(String(50))
    fullname = Column(String(50))
    password = Column(String(12))

    addresses = relationship("Address", backref="user")
    streets = relationship("Street", backref="user")

class Address(Base):
    __tablename__ = 'address'
    id = Column(Integer, primary_key=True)
    email = Column(String(50))
    user_id = Column(Integer, ForeignKey('user.id'))

class Street(Base):
    __tablename__ = 'street'
    id = Column(Integer, primary_key=True)
    name = Column(String(50))
    user_id = Column(Integer, ForeignKey('user.id'))

我正在使用Sqlalchemy ORM插入数据,

jack = User(name='jack', fullname='Jack Bean', password='gjffdd')
jack.addresses = [Address(email='jack@google.com'),Address(email='j25@yahoo.com')]
jack.streets = [Street(name='street1'),Street(name='street2')]
session.add(jack)
session.commit()

以后如何使用Swlalchemy ORM在'adress'表中插入,更新或删除数据。

例如,插入到地址表中,其中user_id等于用户表中“jack”的id。

如果有人将链接传给我,我找不到重新编写此主题的好文档。

2 个答案:

答案 0 :(得分:1)

jacks_new_address = Address(email='newjack@google.com', user = jack)
session.add(jacks_new_address)

要进行更新和删除,您需要先通过查询从DB获取对象,然后更改或.delete()它们。有关如何在SQLAlchemy文档中构建查询对象的大量信息....

答案 1 :(得分:0)

我会执行查询以获取所有User对象,然后像往常一样简单地分配jack.addresses。

jack = session.query(User).filter(User.id == 12345).first()
jack.addresses = [Address(email='jack@google.com'),Address(email='j25@yahoo.com')]