[Fixed]-SQL database (Django) โ€“ Relate all records in table B to each record in table A

1๐Ÿ‘

โœ…

You will need another model, can be Question. The final result would be something like:

class User(models.Model):
    user_name = models.CharField(...)

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

class UserAnswer(models.Model):
    question = models.ForeignKey(Question)
    user = models.ForeignKey(User)
    answer = models.CharField(...)

If you want more complicated answers, like especific values, lists of values, you can create one more model:

class QuestionAlternative(models.Model):
    question = models.ForeignKey(Question)
    value = models.CharField(...)

And then redefine UserAnswer:

class UserAnswer(models.Model):
    question = models.ForeignKey(Question)
    user = models.ForeignKey(User)
    answer = models.ForeignKey(QuestionAlternative)

With this, you will have the Questions in one place, one UserAnswer per question, and the QuestionAlternatives how many times they must exist. Does not worry about the ForeignKey fields, they are not overheads and they build beautiful, reusable structures.

๐Ÿ‘คJean Jung

Leave a comment