Reputation: 155
I have three tables like this,
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'))
I am inserting data using Sqlalchemy ORM like this,
jack = User(name='jack', fullname='Jack Bean', password='gjffdd')
jack.addresses = [Address(email='[email protected]'),Address(email='[email protected]')]
jack.streets = [Street(name='street1'),Street(name='street2')]
session.add(jack)
session.commit()
How i can insert, update or delete data into 'adress' table later using Swlalchemy ORM.
For example , insert into adress table where user_id is equal to id of 'jack' in the user table.
I couldn't find a good documentation regrding this topic, if anyone have just pass me the link.
Upvotes: 0
Views: 1767
Reputation: 590
I would perform a query to grab all the User object, then simply assign jack.addresses as usual.
jack = session.query(User).filter(User.id == 12345).first()
jack.addresses = [Address(email='[email protected]'),Address(email='[email protected]')]
Upvotes: 0
Reputation: 91
jacks_new_address = Address(email='[email protected]', user = jack)
session.add(jacks_new_address)
For updating and deleting, you need to get the object from the DB via a query first, then alter or .delete() them. Loads of information on how to build query objects in the SQLAlchemy documentation....
Upvotes: 1