![](/img/trans.png)
[英]SQLAlchemy: Relationship with ForeignKey consisting of two columns
[英]Use of relationship and ForeignKey modules in SQLAlchemy
对于SQLAlchemy中的两个模块的使用,我有些困惑。 这是我的代码:
Base = declarative_base()
class Restaurant(Base):
__tablename__ = 'restaurant'
id = Column(Integer, primary_key=True)
name = Column(String(250), nullable=False)
class MenuItem(Base):
__tablename__ = 'menu_item'
name =Column(String(80), nullable = False)
id = Column(Integer, primary_key = True)
description = Column(String(250))
price = Column(String(8))
course = Column(String(250))
restaurant_id = Column(Integer,ForeignKey('restaurant.id'))
restaurant = relationship(Restaurant)
我知道ForeignKey用于定义menu_item表的restaurant_id列和restaurant表的id列之间的外键关系。 但是为什么要使用restaurant = Relationship(Restaurant)?
restaurant_id
将引用一个ID(列值)。 restaurant
指的是一个Restaurant
实例,该实例将在访问时从数据库延迟加载(或者如果您之前设置正确的内容,则渴望加载)。 如果在relationship
上设置backref
,则还可以从Restaurant
访问MenuItem
对象的列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.