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.
It is recommended to use the ModelManager for table-level ORM as follows:
Add your custom manager model to TeacherAssignment model class
Now, you can use
TeacherAssignment.objects.get_years()to retrieve all the distinct years that are related to at least one LessonPlan.