[Answer]-Reverse look up based on foreign key queryset data

1👍

This is a bit easier if you add a ManyToManyField to Zone (or Difficulty):

class Zone(models.Model):
    difficulties = models.ManyToManyField(Difficulty, through=Boss, related_name='zones')

Then, you can query for all the difficulties related to a single zone:

for difficulty in zone.difficulties.all():
    bosses = difficulty.boss_set.filter(zone=zone)

To help with performance, use prefetch_related('difficulties'). In Django 1.7 you can use the new Prefetch object to also prefetch the bosses:

# I think that's how the new `Prefetch` works, I haven't actually used it yet.
zone = Zone.objects.prefetch_related(
           Prefetch('difficulties'),
           Prefetch('difficulties__bosses', queryset=Boss.objects.filter(zone_id=zone_id),
       ).get(...)
👤knbk

Leave a comment