Python 多对一关系不返回任何对象:SqlAlchemy

Python 多对一关系不返回任何对象:SqlAlchemy,python,sqlalchemy,many-to-one,Python,Sqlalchemy,Many To One,我正在尝试编写包含如下记录的Schedule类: ... 会话,基地,引擎声明在这里的某个地方 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'))

我正在尝试编写包含如下记录的Schedule类: ... 会话,基地,引擎声明在这里的某个地方

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()
之后,我实现了“Station”类

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

    def __init__(self, name):
         self.name = name
因此,当我尝试添加新的日程记录时,我得到一个错误:

AttributeError: 'NoneType' object has no attribute 'append' 
一对多情况(第一个类中的外键和第二个类中的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))
我得到:

 >>> True
 >>> True
 >>> <class 'sqlalchemy.orm.attributes.InstrumentedAttribute'>
 >>> <class 'NoneType'>
>>正确
>>>真的
>>> 
>>> 
self.station
为无

尝试使用调试器或仅使用
打印站
打印自站

编辑:类变量范围:

类范围变量有两种方式:

  • 实例变量-当使用self时,这称为实例变量,通过该变量,该类的每个实例都将具有该变量的副本

  • Class属性-在您的例子中,它是Schedule.station,它属于类,而不是类的实例

  • 请参考关于名称空间的说明,它将解决您的问题。

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

    因此,要解决我的问题,我只需改变这一点:

    station = relationship("Station", uselist=True)
    
    或在构造函数中使用:

    self.station = station
    

    这完全解决了我的问题。

    我也有类似的问题。我认为问题在于,在你添加并提交之前,这种关系不会被触发

    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)
        session.commit() # IMPORTANT: this is necessary for relationship to work
        print(hasattr(Parent, 'child'))
        print(hasattr(parent, 'child'))
        print(type(Parent.child))
        print(type(parent.child))
    
    我添加的唯一一行是

            session.commit() # IMPORTANT: this is necessary for relationship to work
    

    还可以通过documentationNo,station in not None)中的示例获得此错误,即使它是None,也可以将其添加到任何列表中:
    x=[];x、 追加(无)
    给出
    [None]
    relationsip
    上存在错误,而不是站本身。这是给出错误self.station.append(station)的行,不是吗?这就是我从AttributeError中了解到的:“NoneType”对象没有属性“append”。对不起,我在这里的代码示例中拼写错误
    Station.name==Station\u name
    ,而不是
    Station.name
    。在我的代码中,一切都是正确的(我在这里输入了这段代码,没有复制)np:)只需编辑文章就可以了。还有自助车站吗?它的内容是什么?self.station-据我所知,实际上是对Schedule.station成员的请求。这不是正确的用法吗?
            session.commit() # IMPORTANT: this is necessary for relationship to work