我想知道如何过滤我的定义以仅查看已过滤患者的问题。
我尝试过这个:
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 })
患者=患者_id => 当我使用模板开始 View 时,我得到以下结果:
"Cannot resolve keyword 'patient' into field."
我不知道为什么会发生这个错误,因为当我尝试使用相同参数的另一个解决方案时(病人=病人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_lated 方法过滤我的与 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)
最佳答案
您正尝试按 Question
模型中不存在的字段进行过滤:
Question.objects.filter(patient=patient_id)
患者不是问题
字段,这就是您收到此错误的原因。
在您的 Reply
模型中,将 lated_name
属性添加到问题字段:
question = models.ForeignKey(Question, related_name="replies")
然后您可以通过执行以下操作来查询问题列表以及特定患者的答复:
Question.objects.filter(replies__patient=patient_id)
关于python - 使用 prefetch_lated 进行过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30711036/