简体   繁体   中英

Add foreign key related entities in the same Django admin page

I'm working on a Django app wich will manage some quizes. Those quizes 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)?

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!


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM