[Fixed]-Showing relationships inside the model

1👍

Always 5 Options

Add another field that points to the right option. For example, you could use a ChoiceField that has those choices:

(1, 'option1')
(2, 'option2')
(3, 'option3')
(4, 'option4')
(5, 'option5')

This solution is okay when there are always ever these 5 options.

Free amount of options

In this case, don’t specify options as different fields but use ManyToManyFields and ForeignKeyFields:

class Option(Model):
    text = TextField(unique=True)

class Question(Model):
    quiz_question = TextField(null=False, blank=False)
    answer = TextField()
    options = ManyToManyField(Option)
    selected_option = ForeignKeyField(Option)

Add a validator or clean_selected_option method that controls that the selected option is one of options.

Or use a through model that has an additional column selected:

class QuestionOption(Model):
    option = ForeingKeyField(Option)
    question = ForeignKeyField(Question)
    selected = BooleanField(default=False)

    def clean_selected(self):
        # make sure only one option per question is selected

class Question(Model):
    quiz_question = TextField(null=False, blank=False)
    answer = TextField()
    options = ManyToManyField(Option, through=QuestionOption)

Leave a comment