Search code examples
pythondjangofilterprefetch

filter with prefetch_related


I want to know how I can filter my def to see only questions for the filtered patient.

I have try this:

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 => When I start my views with my template i have this result :

"Cannot resolve keyword 'patient' into field."

I have no idea why this error is happening because when i try another solution with the same argument (patient=patient_id)I have no problem !

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 })

So what is the solution for filter my questions with patient_id with the method prefetch_related ? Thanks you for you help !

This is my 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)

Solution

  • You're trying to filter by a field in the Question model that does not exist:

    Question.objects.filter(patient=patient_id)
    

    patient is not a Question field and this is why you're getting this error.

    In your Reply model, add a related_name property to the question field:

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

    Then you can query the list of questions with replies by a specific patient by doing:

    Question.objects.filter(replies__patient=patient_id)