I wrote a method for registering data using sqlalchemy, but
Error setting foreign key.
In addition, the Belong class id is called as a foreign key in the Page class.
▼ I want to be able to POST.* GET: I was able to retrieve data
a.py 一部Partial excerpt
class PageRepository(): def__init__(self, url): engine=create_engine(url) #Base=declarative_base() Session=sessionmaker (bind=engine) self.session=Session() # page registration def post(self, title, belong_id): now_time = datetime.now() page=Page(id=null, title=title, Belong_id=belong_id, created_at=now_time, updated_at=now_time) self.session.add(page) self.session.commit() page_repository=PageRepository(access_point) page_repository.post('flask test',1)
→ python a.py
results in an error.
Error
sqlalchemy.exc.NoReferencedColumnError: Could not initialize target column for ForeignKey 'belong.id' on table 'page': table 'belong' has no column named 'id'
b.py 一部Partial excerpt
engine=create_engine(access_point, echo=True) Base=declarative_base() class Belong (Base): __tablename__='belong' id=Column('belong_id', Integer, primary_key=True) # pages = relationship ('Page', backref="belong.id") pages=relationship('Page') Base.metadata.create_all(engine) Class Page (Base): __tablename__='page' id=Column('page_id', Integer, primary_key=True) title=Column('title', String(200)) belong_id=Column('belong_id', Integer, ForeignKey('belong.id', onupdate="CASCASE',ondelete="CASCASE")) created_at=Column(DateTime) updated_at=Column(DateTime) Base.metadata.create_all(engine)
I checked many things, but I didn't know...
I would appreciate it if you could tell me how to check.
Thank you for your cooperation.
The error message states that the column named 'id' does not exist in the table 'belong' (table 'belong' has no column named 'id'
).
If you look at the class 'Belong', you define the column name as 'belong_id' as follows:
id=Column('belong_id', Integer, primary_key=True)
Since the table 'belong' does not have a column named 'id', but a column named 'belong_id', modify the description of 'belong_id' in the code of class 'Page' as follows:
belong_id=Column('belong_id', Integer, ForeignKey('belong.belong_id', onupdate="CASCASE", onderlete="CASCASE"))
Alternatively, modify the definition of class 'Belong' as follows:I think I usually take this one.
id=Column (Integer, primary_key=True)
Read the error message carefully.
© 2024 OneMinuteCode. All rights reserved.