I've been trying to figure out whats wrong with this query for a while and am completely stumped.
Basically, I have two tables, a parent table called MainHeatMap and a table of children named MainHeatMapReportLog (structure below)
class MainHeatMap(Base):
__tablename__ = 'MainHeatMap'
MapID = Column(Integer, primary_key=True, autoincrement=True, nullable=False)
Abbrev = Column(String(6), nullable=False, unique=True) #ID for API
Name = Column(String(20), unique=True, nullable=False)
Visible = Column(Boolean(), default=True)
Alert = Column(Boolean(), default=False)
ManualCancelAlert = Column(Boolean(), default=False)
Reports = relationship('MainHeatMapReportLog',
primaryjoin='MainHeatMap.MapID == MainHeatMapReportLog.MapID',
backref='Map', lazy='dynamic'
)
def __init__(self, Name, Abbrev, ManualCancelAlert=False):
self.Name = Name
self.Abbrev = Abbrev
self.ManualCancelAlert = ManualCancelAlert
class MainHeatMapReportLog(Base):
__tablename__ = 'MainHeatMapReportLog'
LogID = Column(Integer, primary_key=True, nullable=False)
MapID = Column(Integer, ForeignKey('MainHeatMap.MapID'), nullable=False)
Status = Column(String(8), index=True)
LogDate = Column(TIMESTAMP(), nullable=False, default=datetime.utcnow())
ReportingApplication = Column(String(15), nullable=False)
Message = Column(String(255))
def __init__(self, Status, ReportingApplication, Message):
self.Status = Status
self.ReportingApplication = ReportingApplication
self.Message = Message
I'm trying to create a query that gives me every record where 'Visible' is set to True in the MainHeatMap table as well as the latest child record (if any) for each in the MainHeatMapReportLog table.
The SQL for this query would be:
SELECT A.MapID, A.Abbrev, A.Name, A.Visible, A.Alert, A.ManualCancelAlert, B.ReportDate
FROM MainHeatMap A
LEFT JOIN (
SELECT MapID, Max(LogDate) as ReportDate
FROM MainHeatMapReportLog
GROUP BY MapID
) B
ON A.MapID = B.MapID
WHERE A.Visible = 1
However, when I try to run the below lines I get the error
'Alias' object has no attribute 'MapID'
LatestReportDate = Session.query(models.MainHeatMapReportLog.MapID,
func.max(models.MainHeatMapReportLog.LogDate).label('ReportDate')
).group_by(models.MainHeatMapReportLog.MapID).subquery()
LatestReports = Session.query(models.MainHeatMap).outerjoin(
(LatestReportDate, (models.MainHeatMap.MapID==LatestReportDate.MapID))
).filter(models.MainHeatMap.Visible==True).all()
The subquery if changed to the .all() method seems to work fine, so it has to be the way I am trying to join the table and subquery together. My google-fu suggests that Alias's are used for self joins, but I don't understand the reference in this case, am I calling models.MainHeatMap incorrectly perhaps?
If anyone could point me in the right direction it would be greatly appreciated.