Shift 'n Tab
Shift 'n Tab

Reputation: 9443

How to get the related field value of item in the queryset inside for loop

Supposed that we have a model Patient and Diagnosis.

class Patient(models.Model):
    name = models.CharField()

class Diagnosis(models.Model):
    patient = models.ForeignKey(
        Patient, 
        related_name='diagnoses', 
        on_delete=models.CASCADE
    )

    is_active = models.BooleanField()

In my views.py i was able to filter Patient whose diagnosis is_active=True with this code.

# returns queryset whose patient has active diagnosis.
queryset = Patient.objects.filter(
    diagnoses__is_active = True
)

But i cannot get the value using for loop with this. I added comment with the errors im getting.

for qs in queryset:
    # 'RelatedManager' object has no attribute 'is_active'
    print qs.diagnoses.is_active 

    # 'Patient' object has no attribute 'diagnoses__is_active'
    print qs.diagnoses__is_active

    # There is no error from this code but 
    # i got the 'diagnoses.Diagnoses.None' in return
    print qs.diagnoses

How can it possibly be when i was able to filter the queryset in the first place?

Upvotes: 0

Views: 675

Answers (2)

Gil Guilherme
Gil Guilherme

Reputation: 252

Because each qs has many diagnoses, ie, qs.diagnoses it's a new queryset. You need to use a iterate do get the diagnoses . Try this:

for diagnose in qs.diagnoses.all():
    print diagnose.is_active

Upvotes: 1

JoseKilo
JoseKilo

Reputation: 2463

Each Patient object will have a collection of Diagnosis objects associated with it.

When you do for qs in queryset:, qs becomes a Patient.

And then, qs.diagnoses is a RelatedManager that can be used to retrieve all the associated Diagnosis objects, but you need to do:

qs.diagnoses.all()

Or maybe

qs.diagnoses.filter(is_active=True) if you are only interested in the actives ones.

Upvotes: 3

Related Questions