Hi,
I have a set of different choices for a question, where each choice has a specific choice value. I need to perform some calculations based on the choice being selected.
I need to get the lowest and highest available value for all the choices a question has. My choice_value
are
choice_value_to_score_map = {
'--': -2,
'-': -1,
'0': 0,
'+': 1,
'++': 2,
}
but not all questions will have the same number of choices and therefore 1 question may have a lower value, i.e. -1
and the highest value of 0
I was thinking I would create a new function within the model, but I canât work out how I get these values cause I am confused about how to get the question id for the question being asked
choices_values = Choice.objects.filter(question__question_id=1).choice_value
but this throws a error:
Related Field got invalid lookup: question_id
I dont understand why Choice.objects.filter(question__question_id=1)
doesnât return the first question
Iâve also tried ProjectQuestionnaireQuestion.objects.get(pk=1)
but this doesnât return a value.
Is this because ProjectQuestionnaireQuestion
has a FK to Questionnaire
class ProjectQuestionnaireQuestion(models.Model):
questionnaire = models.ForeignKey(ProjectQuestionnaire, on_delete=models.CASCADE)
sequence = models.IntegerField()
question = models.TextField()
description = models.TextField(blank=True)
heading = models.CharField(max_length=150, blank=True
If i was to get this working i could then order by highest/lowest and select first/last - Is this the correct approach?
@property
def value_score(self):
return self.lowest_value + self.highest_value
Model
class Choice(models.Model):
question = models.ForeignKey(ProjectQuestionnaireQuestion, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200, null=True)
choice_value = models.CharField(max_length=20, blank=True)
choice_weight = models.DecimalField( max_digits=5, decimal_places=2,blank=True, null=True)
def __str__(self):
return str(self.choice_text)
@property
def raw_score(self):
if not self.choice_value:
return 0
return choice_value_to_score_map.get(self.choice_value, 0)
@property
def weighted_score(self):
return self.raw_score * self.choice_weight
class Meta:
verbose_name = "Report Answer Choice"
choice_value_to_score_map = {
'--': -2,
'-': -1,
'0': 0,
'+': 1,
'++': 2,
}
class ProjectQuestionnaireQuestion(models.Model):
questionnaire = models.ForeignKey(ProjectQuestionnaire, on_delete=models.CASCADE)
sequence = models.IntegerField()
question = models.TextField()
description = models.TextField(blank=True)
heading = models.CharField(max_length=150, blank=True)
...
Thanks