I am facing this InvalidRequestError that my relationships between two classes are not mapped properly. This is one(Question) to Many(Choice) relationship.
from sqlalchemy.ext.declarative import declartive_base
Base = declarative_base()
class ChoiceModel(Base):
__tablename__ = 'choice'
id_seq = Sequence('choice_id_seq', metadata=Base.metadata)
id = Column(Integer, id_seq, server_default=id_seq.next_value(), primary_key=True, index=True)
choice_context = Column(Text, nullable=False)
question_id = Column(Integer, ForeignKey('question.id'))
question = relationship('QuestionModel', back_populates='choices')
class QuestionModel(Base):
__tablename__ = 'question'
id_seq = Sequence('question_id_seq', metadata=Base.metadata)
id = Column(Integer, id_seq, server_default=id_seq.next_value(), primary_key=True, index=True)
correct = Column(Boolean, nullable=False)
choice_list = Column(ARRAY(Integer))
choices = relationship("ChoiceModel", back_populates='question', cascade="all, delete-orphan")
And the error I am getting,
sqlalchemy.exc.InvalidRequestError:
When initializing mapper mapped class ChoiceModel->choice,
expression 'Question' failed to locate a name ('Question').
If this is a class name, consider adding this relationship() to the
<class 'project.core.models.choice_model.ChoiceModel'> class after both dependent classes have been defined.
I have read SQLAlchemy official document similar questions in stackoverflow that most of them used wrong class name, or didn't have back_populates.
My questions are,
should I have to change my classes name, like Choice, Question instead of having postfix Model ?
?
If I mapped correctly, what causes this error?
I have set my PostgreSQL tables name, choice and question
*python==3.10
*ubuntu==20.04
*fastapi==0.73.0
*SQLAlchemy==1.4.31
*postgresql==14.2
Thanks in advance!