Reputation: 109
i am using django last version.I have three table models named like this
Class MCH():
Name= models.CharField()
Class Staff():
Name=models.CharField()
Mch=models.ForeignKey(MCH,,on_delete=models.CASCADE)
location=models.CharField(..)
Class Patients():
Name=models.CharField()
Staff=models.ForeingKey(Staff,on_delete=models.CASCADE)
Phone=models.CharField()
I want to to join the tree table using Django method and filter data by MCH
ServedPatients=Patients.objects. select_related(Staff__MCH='mch1')
Upvotes: 3
Views: 111
Reputation: 476649
You can obtain the data with:
ServedPatients = Patients.objects.select_related('Staff', 'Staff_Mch')
or if you want to filter on the name of the MCH
, you can filter with:
ServedPatients = Patients.objects.filter(Staff__Mch__Name='mch1')
Here you obtain the Patients
objects that have as Staff
an Mch
which has as name 'mch1'
. Here you however will not add the data of the Staff
and Mch
to the relations, you can conmbine the two with:
ServedPatients = Patients.objects.select_related(
'Staff', 'Staff_Mch'
).filter(Staff__Mch__Name='mch1')
Note: normally the name of the fields in a Django model are written in snake_case, not PerlCase, so it should be:
staff
instead of.Staff
Note: normally a Django model is given a singular name, so
Patient
instead of.Patients
Upvotes: 2