Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

533
Views
SQLAlchemy mapping class relationship error

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!

over 4 years ago · Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!