SLATER
SLATER

Reputation: 673

Python/Django - not access to linked model in a generic view

I'm newbie in Python and Django I've 3 models linked: patient -> visit -> prescription

I want to override get_context_data in a detailView to have access to all prescription related to patient visit to patient related_name = 'visits' prescription to visit related_name = 'prescriptions'

but I have an error:

PatientFile object has no attribute 'visits'

I look what is inside self:

patient.views.PatientFile object at 0x04772EB0

I don't understand self is my patient instance so I should have access to all visits with attribute 'visits'?

class PatientFile(DetailView):

    model = Patient
    context_object_name = "patient"
    template_name = "patient/file.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
    context['prescriptions'] = []
    print('self : ', self)
    for visit in self.visits:
        context['prescriptions'].append(visits.prescriptions)
        return context

Upvotes: 1

Views: 107

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476557

The self in your DetailView is the PatientFile view object, not the Patient object.

You can however access the Patient object with self.object [Django-doc]:

class PatientFile(DetailView):

    model = Patient
    context_object_name = 'patient'
    template_name = 'patient/file.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['prescriptions'] = prescriptions = []
        for visit in self.object.visits.all():
            prescriptions.extend(visit.prescriptions.all())
        return context

Note that in order to iterate over a relation, you should use .all(), not just self.visits.

Upvotes: 1

Related Questions