Please help me model this in SQLAlchemy. A user can create a question. A question can have any number of choices (E.g. YES, NO, LATER, MAY BE, DONT KNOW, NEXT YEAR, NOT APPLICABLE). I have created a mapper between questions and choices. How do I model the responses in SQLAlchemy?
question_choices = Table('question_choices', Base.metadata,
Column('id', Integer, primary_key=True),
Column('question_id', Integer, ForeignKey('questions.id')),
Column('choice_id', Integer, ForeignKey('choices.id'))
)
class Choice(Base):
__tablename__ = 'choices'
id = Column(Integer, primary_key=True)
value = Column(String(30), nullable=False)
class Question(Base):
__tablename__ = 'questions'
id = Column(Integer, primary_key=True)
title = Column(String(100))
created = Column(DateTime)
choices = relationship('Choice', secondary=question_choices)
class questionResponse(Base):
"""A friend's response to a question"""
__tablename__ = 'question_responses'
id = Column(Integer, primary_key=True)
question_id = Column(Integer, ForeignKey('questions.id'))
choice_id = Column(Integer, ForeignKey('choices.id'))
user_id = Column(Integer, ForeignKey('users.id'))
created = Column(DateTime)
The questionResponse model is not normalized. Question_id and listing_id are repeated. I do not have a relationship in the mapper table. I want to be able to count the responses for a given question.
Your mapper for
QuestionResponseis pretty good already, but it does not restrict an answer of the choice that is not configured: so ifLATERis not allowed answer for a questionWill you marry me?, the database does not restrict this.One solution to this would be to also add a two-column foreign key constraint to the
QuestionResponse:Alternative (more normalized DB model) is to define the FK only to the
question_choices.id:edit-1: In this case you can have a relationship between Question and QuestionResponse defined like below, which will provide you with count as well:
In any case you might want to add a
UniqueConstraintto thequestion_choicestable on columns(question_id, choice_id).Now, in order to count responses, you either add the relationship between
QuestionandQuestionResponseand returnlen(answers)or you just create a query-based property onQuestion: