Django Queryset with filtering on reverse foreign key Django Queryset with filtering on reverse foreign key django django

Django Queryset with filtering on reverse foreign key


Yes, I think you want

make = Make.objects.get(pk=1)make.make_content_set.filter(published=True)

or maybe

make_ids = MakeContent.objects.filter(published=True).values_list('make_id', flat=True)makes = Make.objects.filter(id__in=make_ids)


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.

class Make(models.Model):    name = models.CharField(max_length=200)class MakeContent(models.Model):    make = models.ForeignKey(Make, related_name='makecontent')    published = models.BooleanField()

I have used the following queryset.

Make.objects.filter(makecontent__published=True)

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 the Makes that contain MakeContents where published = True, and the second is to grab all the MakeContents where published = 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/