Skip to content Skip to sidebar Skip to footer

Django Multiple Queries With Foreign Keys

Let's say I have two different apps : teacher/models.py: Teacher(models.Model): name = models.CharField(max_length=300) class/models.py: Class(models.Model): name

Solution 1:

Use prefetch_related:

teachers = Teacher.objects.prefetch_related('class_set')

# what you want is not a valid Python structure (set of lists (looking like dicts))# list of dicts makes more senseresult = [
    {'teacher': t.pk, 'classes': t.class_set.all()}
    for t in teachers
]

This will only trigger 2 db queries regardless of how many teachers and classes there are.

Post a Comment for "Django Multiple Queries With Foreign Keys"