I am trying to implement an OUTER JOIN
functionality with existing Django features/commands.
I have this model:
class ClinicDoctor(models.Model):
doctor = models.ForeignKey('User', related_name='doctorsF') # single quotes (') because User table is defined down the code.
clinic = models.ForeignKey(Clinic, related_name='clinicsF')
and
class User(AbstractUser):
clinics = models.ManyToManyField(Clinic, through='ClinicDoctor', related_name='doctors')
I need to get list of all doctors along with their associated clinics. I am able to get the list if they have clinics associated with them. But I am not able to get those doctors who have no clinics linked to them.
I tried this:
doctorsQuerySet = ClinicDoctor.objects.filter(doctor__groups__name='Doctor').distinct()
It doesn't work as it does sort of INNER JOIN
This query will give me all the doctors. But I don't know who to proceed to fetch all doctors irrespective clinic associations.
doctorsQuerySet = User.objects.filter(groups__name='Doctor').order_by('full_name')
I have to show clinics along with doctors, if they have any. It seems to be functionality similar to OUTER JOIN
. How do we do it in Django?
Thank you.
If you define doctors as users assigned to the 'Doctor' group, the first query is right:
doctorsQuerySet = User.objects.filter(groups__name='Doctor').order_by('full_name')
By using a loop you can now get over each user and read the data related to the clinics.
for doctor in doctorsQuerySet:
clinics = doctor.clinics.all()
Since this will cause additional queries on every iteration you should consider to use a prefetch in the query:
doctorsQuerySet = User.objects.filter(groups__name='Doctor').prefetch_related('clinics').order_by('full_name')
Hope this helps :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.