我正在尝试在SQLAlchemy中将数据插入到我的数据库中。我以SQLAlchemy documentation suggests:
的方式建立了多对多的关系association_table = Table('association', Base.metadata,
Column('order_id', Integer, ForeignKey('order.id')),
Column('product_id', Integer, ForeignKey('product.id')),
PrimaryKeyConstraint('order_id', 'product_id'))
class Order(Base):
__tablename__ = 'order'
id = Column(Integer, primary_key=True)
date = Column(Date(timezone=False))
product = relationship('Product', secondary=association_table, backref='order')
class Product(Base):
__tablename__ = 'product'
id = Column(Integer, primary_key=True)
name = Column(String(80), nullable=False)
price = Column(Numeric(2))
如何添加数据,以便订单可以包含多个产品,而产品可以包含多个订单(即维护正常的多对多联结表)?
由于order
和product
列都有主键,因此我无法按照一对多的关系执行通常的操作,这类似于
new_entry = Order(date='2015-06-17', product=Product(id=17, 'hardware', 12.15))
session.add(new_entry)
session.commit()
答案 0 :(得分:0)
我能够通过设置Association Object而不是使用链接表来插入新数据。所以设置就是这样的:
class AssociationTable(Base):
__tablename__ = 'associationtable'
product_id = Column(Integer, ForeignKey('product.id'))
order_id = Column(Integer, ForeignKey('order.id'))
product = relationship('Product', backref='parent_assocs')
__table_args__ = (PrimaryKeyConstraint(product_id, order_id), {})
class Order(Base):
__tablename__ = 'order'
id = Column(Integer, primary_key=True)
date = Column(Date(timezone=False))
product = relationship('AssociationTable', backref='parent')
class Product(Base):
__tablename__ = 'product'
id = Column(Integer, primary_key=True)
name = Column(String(80), nullable=False)
price = Column(Numeric(2))
然后我们可以像通常那样通过session
插入值:
new_entry = AssociationTable(order_id=1, product_id=4)
second_entry = AssociationTable(order_id=1, product_id=8)
session.add(new_entry)
session.add(second_entry)
session.commit()