0

我学习 Django 已经有一两个月了,并且没有受过良好的编程教育,所以请耐心等待。它可能比我发现的要容易。

我的项目正在使用各种不同的问题类型从教程中扩展 Polls 应用程序。每种问题类型都有不同的答案字段和选项。根据 Answer_Type 集,我想显示(或不显示)来自模型的相关内联。我发现了如何在 ModelAdmin 中重载“添加”和“更改”视图

class Question(models.Model):  
ANSWER_TYPE_CHOICES = (
        ('CH', 'Choice'),
        ('SA', 'Short Answer'),
        ('LA', 'Long Answer'),
        ('E3', 'Expert Judgement of Probabilities'),
        ('E4', 'Expert Judgment of Values'),
        ('RR', 'Risk Rating'),
        )
answer_type = models.CharField(max_length = 2, 
                               choices= ANSWER_TYPE_CHOICES,
                               default='SA')
question_text = models.CharField(max_length=200, default = "nil")
max_entries = models.IntegerField(default = 1)
man_index = models.IntegerField(default = 0)

和(2个例子 - 第一个不需要内联,第二个需要,以允许每个问题定义风险评级):

    class Long_Answer(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    user = models.ForeignKey(User, on_delete=models.CASCADE, default = 1)
    long_answer = models.CharField(max_length=2000)
    def __str__(self):
        return self.long_answer

class Estimated_risk(models.Model):
# This is for those situations where the aggregate estimate is expected to be a more reliable expert judgment than the paramaterised (prob, cons) estimate.
# Risk value (a number) would be a real-world expected value of losses, for example
# It would be appropriate for a question to have risk and confidence
risk_value = models.DecimalField(max_digits = 4, decimal_places = 3)
risk_definition = models.CharField(max_length = 250)
risk_short_name = models.CharField(max_length = 10)

我写的 admin.py 类意识到我不知道如何解决这个问题(这不起作用,但希望传达我希望发生的事情):

`class QuestionAdmin(admin.ModelAdmin):
    fieldsets = [
    ('Question', {'fields': ['question_text']}),
    ('Type', {'fields': ['answer_type'], 'classes': ['collapse']}),
    ('Maximum Answers per User', {'fields': ['max_entries']}),
    ('Presentation order (unique)', {'fields': ['man_index']}),
    ]

inlines =()
def set_inlines(self, request, object_id, form_url='', extra_context = None):
    if self.fieldsets['Type'] == 'CH':
        return [ChoiceInline]
    if self.fieldsets['Type'] == 'SA':
        return None
    if self.fieldsets['Type'] == 'LA':
        return None
    if self.fieldsets['Type'] == 'E3':
        return None
    if self.fieldsets['Type'] == 'E4':
        return None
    if  self.fieldsets['Type'] == 'RR':
        return [RiskInline]                        

inlines = set_inlines(self)`
4

0 回答 0