공부/python

[FastAPI] Mapper 'Mapper[TableName(tablename)]' has no property 'AnotherTableName'. If this property was indicated from other mappers or configure events, ensure registry.configure() has been called.

조용한외침 2023. 6. 16. 21:59

alembic revision --autogenerate

alembic upgrade head

테이블을 새로 생성하고 기존에 있던 테이블의 데이터를 조회하려고하는데........

 

sqlalchemy.exc.InvalidRequestError: Mapper 'Mapper[User(user)]' has no property 'Question'.  If this property was indicated from other mappers or configure events, ensure registry.configure() has been called.

 

에러가 발생했다.

 

해당 에러를 찾아보고 외래키를 선언하는 부분에서 수정하니 에러는 해결이 됐지만, 다른분들의 블로그 및 코드를 참고하면서 작성하였는데, 저렇게 에러가 나온건 어떤 이유인지 모르겠으나, sqlalchemy에 정의된 User 테이블과 Question테이블의 일대다 관계가 정확하게 명시되지 않아서 발생하는 것 같았다.


해결 방법

 

 

기존 

user_id = Column(Integer, ForeignKey("user.id"))
user = relationship("User", back_populates="user")

변경

user_id = Column(Integer, ForeignKey("user.id"))
user = relationship("user", backref="question")

 

 

- 모델에서 외래키를 선언하는 방법을 바꿔주고 다시 alembic 명령어를 실행해서 해결하였다.

 

 

 

Ref.

https://stackoverflow.com/questions/42139767/sqlalchemy-exc-invalidrequesterror-mapper-has-no-property

 

sqlalchemy.exc.InvalidRequestError: Mapper '...' has no property '...'

I have two classes, TrialIdentifier and TimeCourse TimeCourse has an instance variable containing a TrialIdentifier, and I am trying to setup a foreign key relationship between the two. in

stackoverflow.com

 

- 제가 겪은 오류를 해결하기위해 검색하고 블로그에 작성한 글입니다. 부족한점이 많지만 틀린점이나 부족한점이 있다면 말씀해주시면 감사하겠습니다.