[Fixed]-Creating a variable field in model Django

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.

Leave a comment