多对一关系返回None对象:SqlAlchemy

Mik*_*rev 4 python sqlalchemy many-to-one

我正在尝试编写Schedule类,其中包含这样的记录:... session,base,engine declaration at here ...

class Schedule(Base):
    __tablename__ = 'schedule'
    id = Column(Integer, primary_key=True)
    # and here i need ref to Station class
    station_id = Column(Integer, ForeignKey('station.id'))
    station = relationship('Station') # Also tried Station
    arr_time = Column(Time)

    def __init__(self, station_name, arrive_time):
         self.metadata.create_all()
         self.arrive_time = arrive_time

         # And now I'm trying to find station object by a given name
         # and add ref to it in self.station. 
         # The selection of a station works properly here:
         station = session.query(Station).filter(Station.name == station_name).first()
         # But on this statement I get an error: None object has no method 'append'
         self.station.append(station)
         session.add(self)
         session.commit()
Run Code Online (Sandbox Code Playgroud)

之后我实现了类'Station'

class Station(Base):
    __tablename__ = 'stations'
    id = Column(Integer, primary_key=True)
    name = Column(String)

    def __init__(self, name):
         self.name = name
Run Code Online (Sandbox Code Playgroud)

因此,当我尝试添加新的计划记录时,我收到一个错误:

AttributeError: 'NoneType' object has no attribute 'append' 
Run Code Online (Sandbox Code Playgroud)

一对多的情况(第一类中的外键和第二类中的relationsip)正常工作.

我的代码出了什么问题?

更新: 还尝试了文档中的示例:

engine = create_engine('sqlite:///:memory:')
Base = declarative_base(engine)
session = sessionmaker(bind=engine)()

class Parent(Base):
    __tablename__ = 'parent'
    id = Column(Integer, primary_key=True)
    child_id = Column(Integer, ForeignKey('child.id'))
    child = relationship("Child")

class Child(Base):
    __tablename__ = 'child'
    id = Column(Integer, primary_key=True)


if __name__ == '__main__':
    Base.metadata.create_all()
    parent = Parent()
    session.add(parent)
    child = Child()
    session.add(child)
    print(hasattr(Parent, 'child'))
    print(hasattr(parent, 'child'))
    print(type(Parent.child))
    print(type(parent.child))
Run Code Online (Sandbox Code Playgroud)

我明白了:

 >>> True
 >>> True
 >>> <class 'sqlalchemy.orm.attributes.InstrumentedAttribute'>
 >>> <class 'NoneType'>
Run Code Online (Sandbox Code Playgroud)

Mik*_*rev 5

我已经知道了))问题是因为uselist关系构造函数中的默认标志设置为True.但是 - 我真的不明白为什么它不是用文档编写的 - 在多对一关系的情况下设置这个标志False.

所以,要解决我的问题,我只需要改变这个:

station = relationship("Station", uselist=True)
Run Code Online (Sandbox Code Playgroud)

或在构造函数中使用:

self.station = station
Run Code Online (Sandbox Code Playgroud)

这完全解决了我的问题.