【问题标题】:SQLAlchemy column_property basicsSQLAlchemy column_property 基础知识
【发布时间】:2012-08-23 15:57:52
【问题描述】:

我有两个模型:

class Report(Base):
    __tablename__ = 'report'
    id = Column(Integer, primary_key=True)

class ReportPhoto(Base):
    __tablename__ = 'report_photo'
    id = Column(Integer, primary_key=True)
    report_id = Column(Integer, ForeignKey(Report.id), nullable=False)

    report = relationship(Report, uselist=False, backref=backref('report_photo', uselist=True))

我想在报告模型中添加列,表明 ReportPhoto 中是否有任何记录。我尝试这样使用column_property

class Report(Base):
    __tablename__ = 'report'
    id = Column(Integer, primary_key=True)

    has_photo = column_property(
        select(ReportPhoto.any())
    )

但收到错误NameError: name 'ReportPhoto' is not defined。我该如何解决这个问题?

【问题讨论】:

    标签: python orm sqlalchemy declarative


    【解决方案1】:

    类似的东西应该可以工作:

        class ReportPhoto(Base):
            __tablename__ = 'report_photo'
            id = Column(Integer, primary_key=True)
            report_id = Column(Integer, ForeignKey('report.id'), nullable=False)
    
        class Report(Base):
            __tablename__ = 'report'
            id = Column(Integer, primary_key=True)
            report_photos = relationship(ReportPhoto, backref='report')
            has_photo = column_property(
                exists().where(ReportPhoto.report_id==id)
            )
    

    【讨论】:

      【解决方案2】:

      我将在@Vladimir lliev 的回复中添加一些说明,以向其他可能不知道如何执行此操作的人进行说明。

      将具有“外部表引用”column_property 的表放置在它所引用的之后。在这种情况下,这意味着将 Report 放在 ReportPhoto 之后。这将解决您的 NameError,但是,您的 ReportPhoto 外键引用会留下一个新错误。要解决这个问题,请将您的外键表引用放在引号中。您可以通过参考声明性文档(例如,declarative.py)并在“配置关系”下查看更多信息——具体来说,阅读引用您的外国参考文献的部分。

      使用您的代码,如下所示:

      class ReportPhoto(Base):
          # This now goes first
          __tablename__ = 'report_photo'
          id = Column(Integer, primary_key=True)
          # Notice the quotations around Report references here
          report_id = Column(Integer, ForeignKey("Report.id"), nullable=False)
      
          # Notice the quotations around Report references here
          report = relationship("Report", 
                 uselist=False, 
                 backref=backref("report_photo", uselist=True))
      
      class Report(Base):
          # This is now _after_ ReportPhoto
          __tablename__ = 'report'
          id = Column(Integer, primary_key=True)
      
          # ReportPhoto now exists and we will not trip a NameError exception
          has_photo = column_property(
              select(ReportPhoto.any())
          )
      

      【讨论】:

      • column_property 访问加入的ReportPhoto 记录还是返回一个随机的ReportPhoto 记录?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-04-16
      • 2018-05-25
      • 2014-11-28
      • 2014-02-14
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多