Filtering Django models by existence of a related object

django, django-models

Solution

You can filter users using the backward relation from users to notes, lets try something like this

Note.objects.filter(user__note__color='red')

Problem

Consider the following Django models: ``` class User(models.Model): pass class Note(models.Model): user = models.ForeignKey(User) color = models.CharField() ``` Users might have many notes of different colors. What is the best way to fetch the following query: Get me all notes but only for users which have at least one note which is red The naive way would be to fetch the list of users which have at least one red note and then do a filter on the notes with `user__in=long_list`, but this seems awkward. The solution seems to be around excluding any user without a single red note, but I'm not seeing how this should be done. Additionally, this query will run on very large sets of users and notes, and must be performant. What would be the right way to do this, without resorting to native SQL, unless absolutely neccesary?

Original source