gpt4 book ai didi

python - 多对一关系返回无对象 : SqlAlchemy

转载 作者:太空狗 更新时间:2023-10-30 02:32:15 25 4
gpt4 key购买 nike

我正在尝试编写包含如下记录的 Schedule 类:... session, base, engine declaration 某处...

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' 

一对多情况(第一个类中的外键和第二个类中的关系)工作正常。

我的代码有什么问题?

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

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,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19356362/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com