简体   繁体   English

在同一个Django管理页面中添加与外键相关的实体

[英]Add foreign key related entities in the same Django admin page

I'm working on a Django app wich will manage some quizes. 我正在研究一个可以管理一些问题的Django应用程序。 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. 它们之间存在OneToMany关系,据我所知,应该使用外键建模,在这种情况下,应该在答案实体中建模。

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. 但是,在管理来自Django管理站点的数据时,这非常不方便,因为我首先要定义我的问题,然后在添加答案时,查找问题以填充外键字段。

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)? 以某种方式可能,在添加问题的同时定义所有答案,就像它是一个ManyToMany关系(带有+符号的框等)?

You can use InlineModelAdmin for this. 您可以使用InlineModelAdmin

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! 希望有帮助和快乐的编码!


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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