gpt4 book ai didi

python - SQLAlchemy中关系和外键模块的使用

转载 作者:行者123 更新时间:2023-11-28 21:48:38 29 4
gpt4 key购买 nike

我对使用 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将在访问时从数据库延迟加载的实例(如果您之前设置了正确的内容,则为预加载)。如果你设置 backrefrelationship 上您还可以访问 MenuItem 的列表来自 Restaurant 的对象.

关于python - SQLAlchemy中关系和外键模块的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34958687/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com