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 Make
s and each one's related MakeContent
s where published = True
.
Let me translate Spike's worded answer into codes for future viewers. Please note that each 'Make' can have zero to multiple 'MakeContent'
If the asker means to query 'Make' with AT LEAST ONE 'MakeContent' whose published=True, then Jason Christa's 2nd snippet answers the question.
The snippet is equivalent to
But if the asker means to query 'Make' with ALL 'MakeContent' whose published=True, then following the 'makes' above,
contains the desired query.
I know this is very old question, but I am answering. As I think my answer can help others. I have changed the model a bit as follows. I have used Django 1.8.
I have used the following queryset.
Hope it will help.
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 theMakes
that containMakeContents
wherepublished = True
, and the second is to grab all theMakeContents
wherepublished = 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/
Yes, I think you want
or maybe