python - 使用 prefetch_lated 进行过滤

标签 python django filter prefetch

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

我尝试过这个:

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/

相关文章:

python - 通过比较 pandas 中的一列或多列进行 bool 切片

django - 如何在 Django 中命名模型外键字段?

javascript - 使用 moment.js 按 'last month' 和 'last week' 过滤点击时的对象数组

python - Django 用户授权

python - Pandas 滚动应用功能到整个窗口数据框

python - Django Admin——从 CSV 文件批量创建/导入员工用户

c# - 使用 TextBox 过滤 Datagridview 行

swift - 如何从字典中删除某个 CGPoint

python - 如何使变量等效于其他变量

javascript - 将 JavaScript date() 转换为 Python Django models.DateTimeField