0

I want to ask the user how many questions they want to ask; based on their response, I want to populate a model with those many fields. The way I am currently thinking about doing that is as follows:

from __future__ import unicode_literals
from django.db import models

class Interview(models.Model):
    title = models.TextField()
    description = models.TextField()
    number_questions = models.IntegerField()
    question_one = models.ForeignKey('Question', related_name='question_one')
    question_two = models.ForeignKey('Question', related_name='question_two')
    question_three = models.ForeignKey('Question', related_name='question_three')
    question_four = models.ForeignKey('Question', related_name='question_four')
    question_five = models.ForeignKey('Question', related_name='question_five')

class Question(models.Model):
    question_description = models.TextField()
    prep_time = models.IntegerField()
    response_time = models.IntegerField()

I realize that this solution is inefficient because a) the user is limited to a preset number of questions and b) if the user specifies less than 5 questions, there are unnecessary question entries created. What is a better way to go about storing multiple questions?

1 Answer 1

1

Do the foreign key relation the other way round. That's how you model a many-to-one relation:

class Interview(models.Model):
    title = models.TextField()
    description = models.TextField()

    @property
    def number_questions(self):
        return self.questions.count()

class Question(models.Model):
    interview = models.ForeignKey(Interview, related_name='questions')
    question_description = models.TextField()
    prep_time = models.IntegerField()
    response_time = models.IntegerField()

Now you can access an interview's question via:

interview.questions.all()

An Interview can now have any number of Questions. Btw, the related_name of all the ForeignKeys in your original Interview model should have been 'interview' to make any semantic sense.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.