我有一个模型,Challenge_Question:
class ChallengeQuestion(models.Model):
challenge = models.ForeignKey('Challenge')
question = models.CharField(max_length=500)
displayed_answers = models.IntegerField()
required = models.BooleanField()
multiple_choice = 'MC'
fill_in_the_blank = 'FB'
ordering = 'OR'
true_false = 'TF'
question_choices = (
(multiple_choice, 'Multiple Choice'),
(fill_in_the_blank, 'Fill In The Blank'),
(ordering, 'Ordering'),
(true_false, 'True/False'),
)
question_type = models.CharField(max_length=2, choices=question_choices, default=multiple_choice, db_index=True)
对于每个question_type,我有一个相关的模型FK到ChallengeQuestion:
class ChallengeQuestionMC(models.Model): #for multiple choice questions
question = models.ForeignKey('ChallengeQuestion')
option = models.CharField(max_length=500)
is_answer = models.BooleanField()
class ChallengeQuestionFB(models.Model): #for fill-in-the-blank questions
question = models.ForeignKey('ChallengeQuestion')
option = models.CharField(max_length=100)
sequence = models.SmallIntegerField(default=1, blank=True, null=True)
class ChallengeQuestionTF(models.Model): #for true/false questions
question = models.ForeignKey('ChallengeQuestion')
is_correct = models.BooleanField()
class ChallengeQuestionOR(models.Model): #for ordering type questions
question = models.ForeignKey('ChallengeQuestion')
option = models.CharField(max_length=500)
sequence = models.SmallIntegerField(default=1, blank=True, null=True)
我希望接下来要做的是为每个问题提供适当的管理员内联选项,具体取决于question_type。
例如,如果我填写的是True / False类型的challenge_question,我想要使用True / False" is_correct"可用于检查的字段。如果问题是排序类型,我想在序列字段中提供订购选项。等等。
如果我只是添加到admin.py:
class ChallengeQuestionOptionsInline(admin.StackedInline):
model = ChallengeQuestionMC
extra = 2
class ChallengeQuestionAdmin(admin.ModelAdmin):
inlines = [ChallengeQuestionOptionsInline]
admin.site.register(ChallengeQuestion, ChallengeQuestionAdmin)
然后,这显然不会按照我喜欢的方式运作。我需要在这里有一些条件逻辑,例如"如果challenge_question是question_type' MC'然后使用ChallengeQuestionMC模型。等等。
我还没有找到关于这样的条件逻辑如何在django管理员内联工作的任何内容...任何建议?
答案 0 :(得分:0)
此代码未经测试,因此可能需要调整。但是,在我看来,除了在整个ModelAdmin中全局定义内联之外,您实际上可以通过扩展change_view函数(这是管理系统用来更改特定对象的视图)在本地设置它们。它可能看起来像这样:
class MCInline(admin.StackedInline):
model = ChallengeQuestionMC
class FBInline(admin.StackedInline):
model = ChallengeQuestionFB
class TFInline(admin.StackedInline):
model = ChallengeQuestionTF
class ORInline(admin.StackedInline):
model = ChallengeQuestionOR
class ChallengeQuestionAdmin(admin.ModelAdmin):
def change_view(self, request, object_id, form_url='', extra_context=None):
model = self.model
obj = self.get_object(request, unquote(object_id))
if obj.question_type == 'MC'
self.inlines = [MCInline]
elif obj.question_type == 'FB'
self.inlines = [FBInline]
elif obj.question_type == 'TF'
self.inlines = [TFInline]
elif obj.question_type == 'OT'
self.inlines = [ORInline]
return super(MyModelAdmin, self).change_view(request, object_id,
form_url, extra_context=extra_context)
同样,这是未经测试的,因此很可能需要进行一些调整才能发挥作用。