0

I have following models setup in Django 1.3. I have School and Teacher with many-to-many relationship.

class Teacher(models.Model):
       schools = models.ManyToManyField(School, db_table="schoolteachers", related_name='scteachers')

Now, I have a search view which displays school information. At present, to display teachers for each school, I have a function in School model,

def get_teachers(self):

  return ' , '.join(school.name for school in self.scteachers.all())

So, if we are displaying 50 schools, we are making 50 queries which I want to avoid. I was thinking of using raw_query. But can something else be done?

thanks

mu is too short
  • 426,620
  • 70
  • 833
  • 800
John
  • 3,821
  • 2
  • 18
  • 25

1 Answers1

1
', '.join(School.objects.filter(
  other_way_from_school_to_schoolteachers__teacher__pk=self.pk
  ).values_list('name', flat=True))
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358