I have the following Django model:
class Make:
name = models.CharField(max_length=200)
class MakeContent:
make = models.ForeignKey(Make)
published = models.BooleanField()
I’d like to know if it’s possible (without writing SQL directly) for me to generate a queryset that contains all Makes and each one’s related MakeContents where published = True.
Django doesn’t support the
select_related()method for reverse foreign key lookups, so the best you can do without leaving Python is two database queries. The first is to grab all theMakesthat containMakeContentswherepublished = True, and the second is to grab all theMakeContentswherepublished = True. You then have to loop through and arrange the data how you want it. Here’s a good article about how to do this:http://blog.roseman.org.uk/2010/01/11/django-patterns-part-2-efficient-reverse-lookups/