【问题标题】:Use of relationship and ForeignKey modules in SQLAlchemySQLAlchemy 中关系和 ForeignKey 模块的使用
【发布时间】:2016-04-29 18:15:12
【问题描述】:

我对使用 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) 呢?

【问题讨论】:

    标签: python sqlalchemy


    【解决方案1】:

    restaurant_id 将引用一个 id(列值)。 restaurant 将引用一个 Restaurant 实例,该实例将在访问时从数据库中延迟加载(或者如果您之前设置了正确的内容,则立即加载)。如果您在relationship 上设置backref,您还可以从Restaurant 访问MenuItem 对象列表。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-22
      • 2020-07-21
      • 1970-01-01
      • 2017-09-08
      • 2012-07-28
      • 2014-03-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多