Build a CRUD App with SQLAlchemy - Modeling a many-to-many in SQLAlchemy ORM

To set up a many-to-many in SQLAlchemy:

  • Define an association table using Table from SQLAlchemy
  • Set the multiple foreign keys in the association table
  • Map the association table to a parent model using the option secondary in db.relationship
# Setting up the many-to-many relationship

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)

class Child(Base):
	__tablename__ = 'right'
	id = Column(Integer, primary_key=True)

order_items = db.Table('order_items',
	db.Column('order_id', db.Integer, db.ForeignKey('order.id'), primary_key=True),
	db.Column('product_id', db.Integer, db.ForeignKey('product.id'), primary_key=True)
)

class Order(db.Model):
	id = db.Column(db.Integer, primary_key=True)
	status = db.Column(db.String(), nullable=False)
	products = db.relationship('Product', secondary=order_items,
		backref=db.backref('orders', lazy=True))

class Product(db.Model):
	id = db.Column(db.Integer, primary_key = True)
	name = db.Column(db.String(), nullable = False)
$ python3
>>> from app import db, Order, Product
>>> db.create_all(). # in order to create Order and Product table
>>> order = Order(status='ready') # Order has properties status
>>> product = Product(name='Great Widget') # Product has properties name
>>> order.products = [product] # This order has many products which just include that one product
>>> product.orders = [order]  # This product is many orders that particular list of orders is just one order
>>> db.session.add(order)
>>> db.session.commit() # committing all of the orders and products and as well as there are relationships between the two of them.
>>> exit()
select * from "order";
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值