簡體   English   中英

用prefetch_related過濾

[英]filter with prefetch_related

我想知道如何過濾我的定義,以僅查看針對過濾后患者的問題。

我嘗試了這個:

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方法過濾患者的問題的解決方案是什么? 謝謝您的幫助!

這是我的模型

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)

病人不是“ Question字段,這就是為什么出現此錯誤的原因。

在您的Reply模型中,將一個related_name屬性添加到問題字段:

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

然后,您可以通過執行以下操作來查詢特定患者的帶有答復的問題列表:

Question.objects.filter(replies__patient=patient_id)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM