使用prefetch_related过滤

时间:2015-06-08 13:55:05

标签: python django filter prefetch

我想知道如何过滤我的def以仅查看过滤患者的问题。

我试过这个:

def detail3(request, patient_id):
    patient = get_object_or_404(Patient, pk=patient_id)
    questions = Question.objects.filter(patient=patient_id).prefetch_related('reply_set').all().order_by('pub_date')
    return render_to_response('PQR/detail3.html', {'questions_list': questions, 'patient': patient })

patient = patient_id =>当我用我的模板开始我的观点时,我得到了这个结果:

  

"无法解析关键字'患者'进入领域。"

我不知道为什么会发生这种错误,因为当我尝试使用相同参数的另一个解决方案时(patient = patient_id)我没有问题!

def detail2(request, patient_id):
    tab_replies = []
    patient = get_object_or_404(Patient, pk=patient_id)
    questions = Question.objects.all().order_by('pub_date')
    for question in questions:
        tab_replies.append(question.reply_set.filter(patient=patient_id))
        replies_per_question = zip(questions, tab_replies)    
    return render_to_response('PQR/index.html', {'questions_list': replies_per_question, 'patient': patient })

那么使用prefetch_related方法使用patient_id过滤我的问题的解决方案是什么? 谢谢你的帮助!

这是我的models.py

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

    def __unicode__(self):
        return self.name + ' [' + str(self.id) + ']'

    def listReply(self):
        replies = Reply.objects.filter(patient= self.id)
        return replies

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def __unicode__(self):
        return self.question_text


class Reply(models.Model):
    question = models.ForeignKey(Question)
    patient = models.ForeignKey(Patient)
    reply_text = models.CharField(max_length=200)

    def __unicode__(self):
        return str(self.reply_text)

1 个答案:

答案 0 :(得分:0)

您尝试按Question模型中不存在的字段进行过滤:

Question.objects.filter(patient=patient_id)

患者不是Question字段,这就是您收到此错误的原因。

在您的Reply模型中,将related_name属性添加到问题字段:

question = models.ForeignKey(Question, related_name="replies")

然后,您可以通过以下方式查询特定患者回复的问题列表:

Question.objects.filter(replies__patient=patient_id)
相关问题