ICode9

精准搜索请尝试: 精确搜索
首页 > 数据库> 文章详细

python – SQLAlchemy column_property基础知识

2019-06-30 01:54:32  阅读:598  来源: 互联网

标签: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:名称’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())
    )

标签:python,orm,sqlalchemy,declarative
来源: https://codeday.me/bug/20190630/1331941.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有