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

在尝试使用SQLAlchemy建立多对一关系时,作者遇到了一个问题:当尝试将查询到的Station对象添加到Schedule类的station属性时,出现了'NoneType' object has no attribute 'append'的错误。解决方案在于在定义关系时,需要明确设置`uselist=True`,因为在多对一关系中,默认情况下,关系被设置为单个对象而非列表。
摘要由CSDN通过智能技术生成

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

>>>

>>>

解决方法:

我懂了))

问题是,关系构造函数中的默认uselist标志设置为True.

但是 – 我真的不明白为什么它不是用文档编写的 – 在多对一关系的情况下,这个标志设置为False.

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

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

或在构造函数中使用:

self.station = station

这完全解决了我的问题.

标签:python,sqlalchemy,many-to-one

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值