数据库
首页 > 数据库> > python – 多对一关系返回None对象:SqlAlchemy

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

作者:互联网

我正在尝试编写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'>

解决方法:

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

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

station = relationship("Station", uselist=True)

或在构造函数中使用:

self.station = station

这完全解决了我的问题.

标签:python,sqlalchemy,many-to-one
来源: https://codeday.me/bug/20190529/1176411.html