That looks great Alex, thanks a lot. Also being a Python noob I wasn't aware you could chain together operators in that way. (I assumed, like C# you could only use += or -=, but |= is very cool).
Surrounded by geniuses...I love it! -M On Jan 5, 5:09 pm, "alex.gay...@gmail.com" <alex.gay...@gmail.com> wrote: > You need to build up the Q object and then filter on it so: > results = RelatedModel.objects.all() > q = Q() > for category in category_list: > q |= Q(categories__slug = category.slug) > results = results.filter(q) > > On Jan 5, 10:52 am, Bluemilkshake <bluemilksh...@googlemail.com> > wrote: > > > > > Hello. Django noob here, pretty much. > > > I understand how one can use Q objects to construct OR statements > > within a QuerySet, but (how) is it possible to do this dynamically? > > > I have a list of categories, and I want to find items that match ANY > > of those categories. The current solution doesn't work too well as it > > lists items that match ALL of the categories in the list. This is done > > in this way: > > > results = RelatedModel.objects > > for category in category_list: > > results = results.filter(categories__slug = category.slug) > > > So as you can see this is building an initial resultset of > > RelatedModel objects, then narrowing it down with each iteration > > through my category list (maybe not the most efficient way to do it, > > but the one that made sense to me). Is it possible to do something > > similar, but where Django produces OR statements instead of AND ones, > > or should I just use the extra() function and supply the SQL myself? > > > Thanks a lot for your help. > > -Mark- Hide quoted text - > > - Show quoted text - --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~----------~----~----~----~------~----~------~--~---