繁体   English   中英

如何从 Django 中的多个 ManyToManyField 字段中获取可迭代集合(查询集)?

[英]how to get iterable collection (queryset) from a more than one ManyToManyField field in Django?

我想获取基于特定城市的诊所的医生名单。 我已经开发了一种解决方法,但它似乎很昂贵,因为我正在使用循环来这样做。
诊所 Model:

class Clinic(models.Model):
   clinic_name = models.CharField(max_length=255)
   address = models.CharField(max_length=255, null=True, blank=True)
   doctor = models.ManyToManyField(Doctor, blank=True)
   city = models.ForeignKey(City, on_delete=models.CASCADE)
   latitude = models.CharField(max_length=255, null=True, blank=True)
   longtitude = models.CharField(max_length=255, null=True, blank=True)
   active = models.BooleanField(default=True)
   created_at = models.DateTimeField(auto_now_add=True)

   def __str__(self):
       return self.clinic_name

城市 Model:

    class City(models.Model):
          name = models.CharField(max_length=200)

          def __str__(self):
              return self.name

Model博士:

class Doctor(models.Model):
   user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name="doctor")
   speciality = models.ManyToManyField(Speciality, blank=True)
   service = models.ManyToManyField(Service, blank=True)
   condition = models.ManyToManyField(Condition, blank=True)

   def __str__(self):
       return f"{self.title} {self.user.full_name}"

我的解决方法是:

>>> my_city = City.objects.get(name='Kabul')
>>> clinics = Clinic.objects.filter(city=city)
>>> doctor_list = []
>>> for clinic in clinics:
        doctor_list.extend(clinic.doctor.all())
>>> doctor_list
[<Doctor: Dr. Doctor Khan One>, <Doctor: Prof. Doctor Khan Two>, <Doctor: Dr. Doctor Khan One>, <Doctor: Dr. Doctor Khan One>]
>>> the_result = set(doctor_list)
>>> new_doctor_list = list(the_result)
>>> new_doctor_list
[<Doctor: Dr. Doctor Khan One>, <Doctor: Prof. Doctor Khan Two>]

你可以得到迭代器:

Doctor.objects.filter(clinic__city__name='Kabul').iterator()

或所有对象:

Doctor.objects.filter(clinic__city__name='Kabul').all()

说明:过滤器搜索包含诊所的所有医生,其中包含一个名为“喀布尔”的城市

暂无
暂无

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

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