I'm trying to write a Schedule class that contains these entries: ... session, base, engine declaration somewhere here ...
class Schedule(Base):
__tablename__ = 'schedule'
id = Column(Integer, primary_key=True)
station_id = Column(Integer, ForeignKey('station.id'))
station = relationship('Station')
arr_time = Column(Time)
def __init__(self, station_name, arrive_time):
self.metadata.create_all()
self.arrive_time = arrive_time
station = session.query(Station).filter(Station.name == station_name).first()
self.station.append(station)
session.add(self)
session.commit()
After that, I implement the class 'Station'
class Station(Base):
__tablename__ = 'stations'
id = Column(Integer, primary_key=True)
name = Column(String)
def __init__(self, name):
self.name = name
So, when I try to add a new Schedule entry, I get an error:
AttributeError: 'NoneType' object has no attribute 'append'
The one-to-many case (where the foreign key is in the first class and the relationship in the second) works correctly.
What is wrong with my code?
Update:
Also tried an example from the documentation:
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))
I get:
>>> True
>>> True
>>> <class 'sqlalchemy.orm.attributes.InstrumentedAttribute'>
>>> <class 'NoneType'>