django内联覆盖保存

时间:2015-05-20 15:54:38

标签: python django django-admin

所以我的测试模型包含许多问题。我将它们作为内联在TestAdmin中显示。

class QuestionInline(admin.TabularInline):
    model = Question


class TestAdmin(admin.ModelAdmin):
    inlines = [
        QuestionInline,
    ]

保存后,我有覆盖保存方法,我计算测试的最大结果:

def save(self, *args, **kwargs):
    super(Test, self).save(*args, **kwargs)
    max_result = 0

    for question in Question.objects.filter(test=self):
        if question.calculate_stress_level and question.type != "0" and question.type != "1" and question.type != "10" and question.type != "11":
            max_choice = 0

            for choice in AnsweredQuestion.ALL_CHOICES[question.type]:
                if max_choice < int(choice[0]):
                    max_choice = int(choice[0])

            max_result += max_choice

    self.max_result = max_result

    super(Test, self).save(*args, **kwargs)

但是,当调用save方法时,问题值没有被更新,因此我必须保存模型两次。为什么会这样,我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

必须首先保存父对象才能写入m2m字段。请查看How to create an object for a Django model with a many to many field?以获取有关类似主题的讨论。