Problem with quering a many to one in django
Im fairly new to Django, I was attempting to make a many to one query in my program. Im making af clinic site, in which I want a list of patients for the given clinic to be shown.
I have the following Model.py and views.py:
models.py
class Klinik(models.Model):
class Patient(models.Model):
klinik = models.ForeignKey(Klinik, null=True, on_delete=models.SET_NULL)
views.py
def kartotek(request, kl_id):
klinikid = Klinik.objects.get(id=kl_id)
patienter = Klinik.Patient_set.all()
context = {'patients':patienter,}
return render(request,'DentHelp/kartotek.html', context )
The error message is for the _set.all() attribute, but I cant see what the problem should be
after getting the Klinik object, to fetch all patients linked to it you should use the object
like this: klinikid.patient_set.all()
patient_set is lowercase, and from the object, not the class Klinik
Also you can give to Patient field klinik a related name, this related_name will "override" the modelname_set more on doc https://docs.djangoproject.com/en/4.0/topics/db/queries/#backwards-related-objects