ArgumentError: relationship expects a class or map

2019-01-24 02:29发布

问题:

I am getting this strange error, and I'm saying strange because I made a change to an unrelated table.

I am trying to query my tDevice table which looks like this:

class TDevice(Base):
    __tablename__ = 'tDevice'

    ixDevice = Column(Integer, primary_key=True)
    ixDeviceType = Column(Integer, ForeignKey('tDeviceType.ixDeviceType'), nullable=False)
    ixSubStation = Column(Integer, ForeignKey('tSubStation.ixSubStation'), nullable=False)
    ixModel = Column(Integer, ForeignKey('tModel.ixModel'), nullable=True)
    ixParentDevice = Column(Integer, ForeignKey('tDevice.ixDevice'), nullable=True)
    sDeviceName = Column(Unicode(255), nullable=False)#added

    children = relationship('TDevice',
                        backref=backref('parent', remote_side=[ixDevice]))

    device_type = relationship('TDeviceType',
                           backref=backref('devices'))

    model = relationship('TModel',
                     backref=backref('devices'))

    sub_station = relationship('TSubStation',
                           backref=backref('devices'))

and this is how I query it:

Device = DBSession.query(TDevice).filter(TDevice.ixDevice == device_id).one()

as soon as this line is executed, I get the error:

ArgumentError: relationship 'report_type' expects a class or a mapper argument (received: <class 'sqlalchemy.sql.schema.Table'>)

The only changes I've made is add a report_type relationship in my tReportTable which now looks like this:

class TReport(Base):
__tablename__ = 'tReport'

ixReport = Column(Integer, primary_key=True)
ixDevice = Column(Integer, ForeignKey('tDevice.ixDevice'), nullable=False)
ixJob = Column(Integer, ForeignKey('tJob.ixJob'), nullable=False)
ixReportType = Column(Integer, ForeignKey('tReportType.ixReportType'), nullable=False) # added

report_type = relationship('tReportType',
                           uselist=False,
                           backref=backref('report'))

device = relationship('TDevice',
                      uselist=False,
                      backref=backref('report'))

job = relationship('TJob',
                   uselist=False,
                   backref=backref('report'))

I'm still new to SqlAlchemy so I can't seem to see how adding that relationship should be causing this error if I am iterating another table

回答1:

not happy with myself since it's such a dumb mistake but here is my culprit:

report_type = relationship('tReportType',
                           uselist=False,
                           backref=backref('report'))

should be:

report_type = relationship('TReportType',
                           uselist=False,
                           backref=backref('report'))

capital T instead of t, I should be referencing the class, not my actual table name: 'tReportType' -> 'TReportType'