Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Queryset with filtering on reverse foreign key

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.

like image 265
Julian A. Avatar asked Mar 25 '11 19:03

Julian A.


1 Answers

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) 
like image 138
Jason Christa Avatar answered Sep 22 '22 19:09

Jason Christa