[Answered ]-Django: left outer join (how to preselect a related object from "many" side)

2👍

✅

You use QuerySet.prefetch_related.

Unfortunately, prefetch_related doesn’t support filtering (yet), and filter-ing on the Member.media_set QuerySet will create a new database query.

You have two options here:

  • Do the filtering in Python to find Media with profile == True
  • Wait for Django 1.7 and use the new Prefetch lookup object.

If you were to do the filtering in Python, you would do something like:

profile_pictures = [media for media in member.media_set.all() if media.profile]

This will be faster than querying the database if you don’t have too many images. You’ll want to benchmark.

Leave a comment