from sqlalchemy import create_engine, Column, Integer, Table, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, sessionmaker
Base = declarative_base()
association_table = Table('association', Base.metadata,
Column('left_id', Integer, ForeignKey('left.id')),
Column('right_id', Integer, ForeignKey('right.id'))
)
class Parent(Base):
__tablename__ = 'left'
id = Column(Integer, primary_key=True)
children = relationship("Child", secondary=association_table, backref="parent")
def __repr__(self):
return '<Parent(id={})>'.format(self.id)
class Child(Base):
__tablename__ = 'right'
id = Column(Integer, primary_key=True)
def __repr__(self):
return '<Child(id={})>'.format(self.id)
engine = create_engine('mysql://{login}:{password}@{server}:{port}/{db}'.format(
login='test',
password='test',
server='localhost',
port=3306,
db='test',
))
session = sessionmaker(bind=engine)()
# -------------------------------------------------------------------------------
p1 = Parent(id=1)
p2 = Parent(id=2)
c1 = Child(id=1)
c2 = Child(id=2)
c3 = Child(id=3)
p1.children = [c1, c2]
p2.children = [c2, c3]
session.add(p1)
session.add(p2)
session.commit()
print '{} childrens: {}'.format(p1, p1.children)
print '{} parents: {}'.format(c2, c2.parent)
Вывод:
<Parent(id=1)> childrens: [<Child(id=1)>, <Child(id=2)>]
<Child(id=2)> parents: [<Parent(id=1)>, <Parent(id=2)>]