Add foreign key related entities in the same Django admin page

Question:

I’m working on a Django app which will manage some quizzes. Those quizzes are formed by a question and some possible answers, which I’ve defined as different models.

There is an OneToMany relationship between them, which as far as I know, should be modeled with a foreign key, in this case, in the answer entity.

However, while managing the data from the Django administration site, this is quite inconvenient, because I’ve to define first my question, and later, while adding the answers, look for the question in order to fill the foreign key field.

Would be somehow possible, to define all the answers while adding the question, in a similar way as if it was a ManyToMany relationship (the box with the + symbol, etc.)?

Asked By: pitazzo

||

Answers:

You can use InlineModelAdmin for this.

In your case, this could look something like:

from django.contrib import admin

class AnswerInline(admin.StackedInline):
    model = Answer
    extra = 1  # If you have a fixed number number of answers, set it here.

class QuestionAdmin(admin.ModelAdmin):
    model = Question
    inlines = [
        AnswerInline,
    ]

# don't forget to register your model
admin.site.register(Question, QuestionAdmin)

     Hope that helps and happy coding!

Answered By: j-i-l