【问题标题】:django inlines override savedjango 内联覆盖保存
【发布时间】:2015-08-01 23:54:26
【问题描述】:

所以我有一个包含许多问题的测试模型。我在 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 方法时,问题值没有被更新,因此我必须保存模型两次。为什么会这样,我该如何解决?

【问题讨论】:

    标签: python django django-admin


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-01
      • 1970-01-01
      • 2011-08-17
      • 2018-10-07
      • 1970-01-01
      • 2020-01-12
      • 2019-07-09
      相关资源
      最近更新 更多