Home > Mobile >  Django Filter get value from field
Django Filter get value from field

Time:07-15

How do I get the value from a field after a running filter?

all_q_answered = ProjectQuestionnaireAnswer.objects.filter(response = q_response, answer__isnull=False)

I need to get the values of the field choice_weight from the returned queryset?

The ProjectQuestoinnaireAnswer model has a fk to a Choices model that has a choice weight value

class ProjectQuestionnaireAnswer(models.Model):
    YN_Choices = [
        ('Yes', 'Yes'),
        ('No', 'No'),
        ('Unknown', 'Unknown')
    ]
    question = models.ForeignKey(ProjectQuestionnaireQuestion, on_delete=models.CASCADE)
    answer = models.ForeignKey(Choice, on_delete=models.CASCADE,null=True)
    value = models.CharField(max_length=20, blank=True)
    notes = models.TextField(blank=True)
    response = models.ForeignKey(ProjectQuestionnaireResponse, on_delete=models.CASCADE)

class Choice(models.Model):
    question = models.ForeignKey(ProjectQuestionnaireQuestion, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    choice_value = models.CharField(max_length=20, blank=True)
    choice_weight = models.IntegerField(blank=True, null=True)

Thanks

CodePudding user response:

You can use values() method:

all_q_answered = ProjectQuestionnaireAnswer.objects.filter(response = q_response, answer__isnull=False).values('answer__choice_weight')

It will give something like:

<QuerySet [{'choice_weight': 'first_choice'}, {'choice_weight': 'second_choice'}]>

CodePudding user response:

all_q_answered = ProjectQuestionnaireAnswer.objects.filter(response = q_response, answer__isnull=False).values('answer__choice_weight')

You can use __ to get the values of related objescts.

  • Related