Reputation: 2003
I have the following model structure:
class Answer(models.Model):
id = models.IntegerField(primary_key=True)
answer_text = models.CharField(max_length=150)
def __str__(self):
return self.answer_text
class Question(models.Model):
question_text = models.CharField(max_length=150)
choices = models.ForeignKey(Answer, on_delete=models.CASCADE,
related_name='choices')
answer = models.OneToOneField(Answer, on_delete=models.CASCADE)
def __str__(self):
return self.question_text
I have registered both the models on admin. But when I try to add multiple choices to a question in the admin, it does list any other answers.
See the attached screenshot. I am unable to add multiple choices for a question. When I click the green + button, it does not list all possible answers.
Upvotes: 1
Views: 4970
Reputation: 599630
Your foreign key is the wrong way round. The model the field is defined on is the "many" side of the one-to-many relationship.
For a question that has multiple answers, the FK should live on Answer pointing to Question.
You can then use the "inlines" feature of the admin to define multiple answers on the same page as the question.
Upvotes: 4
Reputation: 47364
You can use in this case ManyToManyField
. This allows you to bind multiple choices to different questions at the same time:
choices = models.ManyToManyField(Answer, related_name='choices')
Upvotes: 1