On Fri, 2009-03-13 at 12:02 -0700, Adam Nelson wrote: > If I have a QuerySet like this: > > >>> o1 = Store.objects.all() > >>> for o2 in o1: > ... o2.employees.all() > ... > [<Employee: Adam>, ...] > > > Is there any way to get all employees for all stores without having to > do the for (in other words some sort of one line solution)? I seem to > need to do this frequently and it seems wasteful Something like > o1.employees.all() would be ideal but if o1 is a QuerySet, that won't > work. > > Thanks for any help, even if I can just get a definitive 'no - that's > the best way to do it'.
A bit tricky to answer specifically without knowing the models involved, but here's the general idea: "Reverse the direction" (my own term) of the queryset. You want a collection of employees based on some constraint on the Store, so the one-liner, if it exists, will be an Employee queryset. Assuming this model (see what a difference details make! :-)): from django.contrib.auth import models as auth_models class Store(models.Model): employees = models.ManyToMany(auth_models.User) ... you can get all employees involved in any store at all with: User.objects.exclude(store=None) In other words, filter the employees by throwing away any that are attached to any store (the remainder are part of a the Store.objects.all() set of stores). You can pretty much always turn around the direction of querysets like this when doing nested loops. Then you get back all the data with only query and can now iterate through it in Python to process things further. However, there's one problem in this case (with many-to-many): you can't work out which store they're attached to without another database query. This is because each employee could be attached to many stores, so it's hard to do implement select_related() for multi-valued relations in a way that doesn't make it easy to shoot yourself in the foot (which is why it's not in Django yet). The difficulties there have been discussed on this list in the past. Regards, Malcolm --~--~---------~--~----~------------~-------~--~----~ 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 -~----------~----~----~----~------~----~------~--~---