Django models for questionaire with questions with different answer types

This question is similar to Designing Django models for questions to have different answer types but hopefully more specific. For my particular case I can see different ways for an implementation but I am not sure what a good way would be.

I have a base usermodel. Users are presented with a questionnaire which can be the same for different user but can also be different from one user to another and also might be different on different days for a single user. Each questionnaire has different questions and the questions might have different answer types (text, int, etc). At the end I want a list of the questionnaires with answers for a specific user (e.g. of the past week for user X).

I guess one way to implement this would be to only have one answer type (text) and let the form handle the validation and let the view handle the rendering with correct answer formatting:

class Question(models.Model):
    question_text = models.CharField()
    answer_type = models.CharField()

class Questionnare(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    questions = models.ManyToManyField(Question, through='Answer')
    date = models.DateField(auto_now_add=True)

class Answer(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    questionnaire = models.ForeignKey(Questionnare, on_delete=models.CASCADE)
    answer = models.TextField()

Maybe another way would be to have different Answer classes and multi-inheritance as described here. (Haven't tested this so far.)

Or I could have different Answer classes without a Questionnaire model, query the different Answer models (by date+user) and then patch things together in the corresponding view.

What would be the 'best' option or do you have any other ideas? (The number of questions will probably be the least, then number of users.)

Back to Top