Quering distinct values throught related model

Posted by matheus.emm on Stack Overflow See other posts from Stack Overflow or by matheus.emm
Published on 2011-01-11T00:49:04Z Indexed on 2011/01/11 0:53 UTC
Read the original article Hit count: 275

Filed under:
|

Hi! I have a simple one-to-many (models.ForeignKey) relationship between two of my model classes:

class TeacherAssignment(models.Model):
    # ... some fields
    year = models.CharField(max_length=4)

class LessonPlan(models.Model):
    teacher_assignment = models.ForeignKey(TeacherAssignment)
    # ... other fields

I'd like to query my database to get the set of distinct years of TeacherAssignments related to at least one LessonPlan. I'm able to get this set using Django query API if I ignore the relation to LessonPlan:

class TeacherAssignment(models.Model):
    # ... model's fields
    def get_years(self):
        year_values = self.objects.all().values_list('year').distinct().order_by('-year')
        return [yv[0] for yv in year_values if len(yv[0]) == 4]

Unfortunately I don't know how to express the condition that the TeacherAssignment must be related to at least one LessonPlan. Any ideas how I'd be able to write the query?

Thanks in advance.

© Stack Overflow or respective owner

Related posts about django

Related posts about django-models