mohamed abdallah
mohamed abdallah

Reputation: 109

Django retrieve data from three tables

Question

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

I tried this

ServedPatients=Patients.objects. select_related(Staff__MCH='mch1')

Upvotes: 3

Views: 111

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

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

Related Questions