Reputation: 2388
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.
Upvotes: 0
Views: 400
Reputation: 1061
It is recommended to use the ModelManager for table-level ORM as follows:
class TeacherAssignmentManager(models.Manager):
def get_years(self):
year_values = self.filter(lessonplan__isnull=False).\
values_list('year').distinct().\
order_by('-year')
return [yv[0] for yv in year_values if len(yv[0]) == 4]
Add your custom manager model to TeacherAssignment model class
objects = TeacherAssignmentManager()
Now, you can use TeacherAssignment.objects.get_years()
to retrieve all the distinct years that are related to at least one LessonPlan.
Upvotes: 1
Reputation: 118438
TeacherAssignment.objects.filter(lessonplan__isnull=False)
Satisfies your query. Get all TeacherAssignments that have a LessonPlan.
Reverse relationships can be queried this way from the parent model.
Upvotes: 0