1

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.

Devasta
  • 1,489
  • 2
  • 17
  • 28
  • 1
    Try `models.MainHeatMap.MapID==LatestReportDate.c.MapID` in the `join` condition instead. – van Oct 31 '14 at 08:56
  • 1
    Also take a look at the recent very similar question and the answer [http://stackoverflow.com/a/26483320/99594], where you are able to load the whole instance of the related table (`MainHeatMapReportLog`) instead of only the field. It also solves a duplicate result problem in case you have multiple `MainHeatMapReportLog` with the same *latest* `LogDate`. – van Oct 31 '14 at 09:01
  • Hi Van, Many thanks for your answer, I am giving it a try now and looking at the link you have provided. Another question, if you don't mind: What does the 'c' that I am including in the query do? – Devasta Oct 31 '14 at 20:59
  • 1
    This is an alias for `columns`, see [`sqlalchemy.sql.expression.Select.c`](http://docs.sqlalchemy.org/en/rel_0_9/core/selectable.html#sqlalchemy.sql.expression.Select.c) documentation. – van Nov 01 '14 at 04:34

0 Answers0