python – SQLAlchemy column_property基础知识

我有两个型号:

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:名称’ReportPhoto’未定义.我该如何解决这个问题?

解决方法:

我将添加@Vladimir lliev的回复,并对可能看不到如何做到这一点的其他人做出一些澄清.

将引用了“外表引用”column_property的表放在它引用的表之后.在这种情况下,它意味着在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())
    )
上一篇:编程范式:命令式编程(Imperative)、声明式编程(Declarative)和函数式编程(Functional)


下一篇:python – 如何断言Pyke中的负面事实?