在SQLAlchemy中建模多项选择题和正确答案

时间:2020-11-04 15:10:08

标签: python sqlalchemy

我正在SQLA 1.3中定义一个简单的一对多关系:

class Question(Base):
    """ Quiz questions """

    __tablename__ = "question"
    id = Column(Integer, primary_key=True)
    question_text = Column(Unicode(250), index=True)
    answers = relationship("Answer", back_populates="question")


class Answer(Base):
    """ Answers to quiz questions """

    __tablename__ = "answer"
    id = Column(Integer, primary_key=True)
    question_id = Column(Integer, ForeignKey("question.id"))
    answer_text = Column(Unicode(250), index=True)
    question = relationship("Question", back_populates="answers")

但是我也想指定答案之一是正确。我无法添加例如answer_id外键和correct_answer = relationship("Answer", uselist=False, foreign_keys=[answer_id])Question的原因,因为这会引发AmbiguousForeignKeysError。还有其他方法可以做到这一点吗?

2 个答案:

答案 0 :(得分:1)

您可能有正确的答案交集表,例如

public class SNGUI {
public JFrame f = new JFrame();

JPanel panelright = new JPanel(); //contains UT/LWmenu/MetaMenu
JPanel panelleft = new JPanel(); //contains TextArea document / TextEditors
JPanel TextEditorsPanel = new JPanel();
JPanel UpperToolsPanel = new JPanel();
JPanel LowerToolsPanel = new JPanel();
JPanel SettingsPanel = new JPanel();

public SNGUI() {

    //Frame characteristics
    f.setTitle("Study Notes v 0.00.0");
    f.setSize(1440,900);
    f.setExtendedState(JFrame.MAXIMIZED_BOTH);
    f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    f.setLayout(new GridLayout(1,2));
    f.setResizable(true);
    f.setVisible(true);

    // Main panel layouts
    panelright.setLayout(new BorderLayout());
    panelleft.setLayout(new BorderLayout());

    // Additional panel layouts
    //TextEditors.setLayout(new FlowLayout(FlowLayout.LEADING,0,0));

    // Lower Tools Buttons
    LTButtons[0] = new JButton("Calculator");

    // colors (delete later)
    panelleft.setBackground(Color.yellow);
    panelright.setBackground(Color.DARK_GRAY);
    TextEditorsPanel.setBackground(Color.GREEN);
    UpperToolsPanel.setBackground(Color.blue);
    LowerToolsPanel.setBackground(Color.cyan);
    SettingsPanel.setBackground(Color.pink);

    //panelright.setPreferredSize(new Dimension(1000,100));


    panelleft.add(TextEditorsPanel, BorderLayout.NORTH);
    panelright.add(UpperToolsPanel, BorderLayout.NORTH);
    panelright.add(LowerToolsPanel, BorderLayout.SOUTH);
    panelright.add(SettingsPanel, BorderLayout.EAST);
    f.add(panelleft);
    f.add(panelright);

}

public static void main(String[] args) {
    SNGUI StudyNotes = new SNGUI();
}

约束是,如果您想假设每个问题最多具有一个正确答案。

答案 1 :(得分:1)

为什么不将简单的correct_answer_flag列添加到“答案”表,并为每个正确回答的问题标记“ Y”或“ N”。