Python 与预取相关的过滤器
我想知道如何过滤def以仅查看过滤后患者的问题 我试过这个:Python 与预取相关的过滤器,python,django,filter,prefetch,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 r
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\u id=>当我使用模板启动视图时,我得到以下结果:
“无法将关键字“patient”解析为字段。”
我不知道为什么会发生这种错误,因为当我尝试使用相同参数(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 })
那么,使用“预回迁”相关方法过滤患者id的问题的解决方案是什么?
谢谢你的帮助
这是我的模特
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.objects.filter(patient=patient_id)
患者不是问题
字段,这就是为什么会出现此错误
在您的回复
模型中,向问题字段添加相关名称
属性:
question = models.ForeignKey(Question, related_name="replies")
然后,您可以通过执行以下操作查询特定患者的问题列表和答复:
Question.objects.filter(replies__patient=patient_id)
你能附上
问题
模型吗?那么我如何才能获得完整的问题列表,以及如果适用于我的患者,相关的回答!附加患者模型会有所帮助。:)我已替换为Question.objects.filter(Question\u set\u patient=patient\u id)
,现在我有一个错误:无法将关键字'Question\u set'解析到字段中。我已获得questions=Question.objects.filter(Question\u set\u patient=patient\u id)。预回迁相关('reply\u set').all().order\u by('pub\u date')
你有什么想法吗?:)