SQLAlchemy basics column_property

I have two models:

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

And I would like to add a column to the report model that indicates if there are records in ReportPhoto. I am trying to use column_property as follows:

 class Report(Base): __tablename__ = 'report' id = Column(Integer, primary_key=True) has_photo = column_property( select(ReportPhoto.any()) ) 

but get an error NameError: name 'ReportPhoto' is not defined . How can I fix this problem?

+4
source share
2 answers

I will add @Vladimir lliev to the answer with some clarification for anyone else that might not see how to do this.

Place a table that will reference the 'external table referencing' column_property after it is referenced. In this case, this means placing the report after ReportPhoto. This will solve your NameError, however, you will still have a new error in your link to the ReportPhoto foreign key. To resolve this problem, place the link to the foreign key table in quotation marks. You can read more by referring to declarative documentation (for example, declarative.py) and looking in the section "Setting up relationships" - in particular, read this part when quoting your foreign links.

With your code, it will look like this:

 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()) ) 
+1
source

something like this should work:

  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) ) 
+2
source

All Articles