Search code examples
djangoormmany-to-many

Django query get all A records with B records


My Django project has a many to many relationship Doctor -- Speciality I'm trying to list only specialties with doctor records to allow users request an appointment.

Just now I have this

context['specialities'] = [s for s in Speciality.objects.all() if s.doctor_set.all()]

but it's not an elegant solution. I wanna list only specialties with active (is_active=True) doctors.

How can I add is_active filter?

Update! OP here.

[s for s in Speciality.objects.all() if s.doctor_set.filter(is_active=True)]

It works, but it still is a non-elegant solution. Any nice query which solves the problem?

Updated! OP here. Model.

class Speciality(models.Model):
  name = models.CharField(max_length=64)
class Doctor(models.Model):
  name = models.CharField(max_length=64)
  specialities = models.ManyToManyField(Speciality)
  is_active = models.BooleanField(default=True)

Solution

  • Simply,

    speciality_qs = Speciality.objects.filter(doctor__is_active=True).distinct()