SQLAlchemy column_property基础知识

时间:2012-08-29 05:02:53

标签: python orm sqlalchemy declarative

我有两种模式:

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))

我想在Report模型中添加一列,表明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。我如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

这样的事情应该有效:

    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)
        )

答案 1 :(得分:1)

我将添加@Vladimir lliev的回复,并对可能看不到如何执行此操作的其他人做出一些澄清。

在引用的表之后放置将具有“外部表引用”column_property 的表。在这种情况下,它意味着在 ReportPhoto之后放置Report 。这将解决您的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())
    )