7

我有两个模型:

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。我该如何解决这个问题?

4

2 回答 2

6

类似的东西应该有效:

    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)
        )
于 2012-08-31T23:23:41.340 回答
4

我将在@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())
    )
于 2014-01-06T04:57:06.683 回答