0

So I have Test model that contains a number of questions. I display them in TestAdmin as inlines.

class QuestionInline(admin.TabularInline):
    model = Question


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

And upon save I have overriden save method where I calculate test's max result:

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)

However when save method is invoked question values are not being update, therefore I have to save model two times. Why is this and how can I fix this ?

Marijus
  • 4,195
  • 15
  • 52
  • 87

1 Answers1

0

Parent object has to be saved first in order to have its m2m fields written. Please check How to create an object for a Django model with a many to many field? for a discussion on similiar topic.

Community
  • 1
  • 1
jacekbj
  • 631
  • 3
  • 10