I am using django 0.96.1 mostly for its database API on a large project. I need to retrieve many-ended relationship data. For example, for every user, I need to know what groups they are in. As expected, there is a many-to-many relationship.
The code I've written will get a queryset of users filtered by some arbitrary criteria, call the values() method, and then iterate over the results. For each row, it calls a "getter" for the group relationship. That getter receives a parameter current_user_id and does this: group.objects.filter(user__id__exact = current_user_id).values('id') It then converts the list of dictionaries into just a list of integers, and returns the results. This way I am augmenting the user.objects.values() result set with lists of foreign keys representing the many-end of a relationship. I end up with results looking like this: [{ 'username' : 'jshmoe', 'first_name' : 'Joe', 'last_name' : 'Shmoe', 'groups' : [ 3, 5, 6, 14] }] The problem is that this is slow, I think because it's executing a new database query for each user. It's even worse because many objects in my data model have several many-ended relationships. Using 6 such getters on 1000 users is taking about 8 seconds to return, running on respectable hardware. Is there an appropriate django way to run only one query to retrieve all of these results? I guess all I really need is the contents of the user_groups table, filtered by some collection of user ids. Then I can do the matching myself in code. Thanks for your help, Michael
signature.asc
Description: This is a digitally signed message part.