gpt4 book ai didi

python - SQLAlchemy column_property 基础知识

转载 作者:太空狗 更新时间:2023-10-30 02:22:10 27 4
gpt4 key购买 nike

我有两个模型:

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

最佳答案

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

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

关于python - SQLAlchemy column_property 基础知识,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12171189/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com