简体   繁体   English

Django:返回匹配和不匹配的记录

[英]Django: Return matching and non-matching records

I am trying to implement an OUTER JOIN functionality with existing Django features/commands. 我正在尝试使用现有的Django功能/命令实现OUTER JOIN功能。

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 它不起作用,因为它确实可以进行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 . 它的功能似乎类似于OUTER JOIN How do we do it in Django? 我们如何在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 :) 希望这可以帮助 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM