如何获取for循环中查询集中item的相关字段值

时间:2017-02-21 09:55:25

标签: django django-queryset

假设我们有一个模型PatientDiagnosis

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()

在我的views.py中,我能够使用此代码过滤诊断为is_active=True的患者。

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

但我无法使用for循环获取该值。我添加了关于错误的评论。

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

当我能够首先过滤查询集时,怎么可能呢?

2 个答案:

答案 0 :(得分:3)

每个Patient对象都有一组与之关联的Diagnosis对象。

当您执行for qs in queryset:时,qs成为患者。

然后,qs.diagnosesRelatedManager,可用于检索所有关联的诊断对象,但您需要这样做:

qs.diagnoses.all()

或者

qs.diagnoses.filter(is_active=True)如果你只对活跃的那些感兴趣。

答案 1 :(得分:1)

因为每个qs都有很多诊断,即qs.diagnoses它是一个新的查询集。你需要使用迭代来做诊断。试试这个:

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