Skip to content
Browse files

Optimize the friends_for_user method to do 50% fewer SQL queries.

  • Loading branch information...
1 parent ab5aca0 commit 00e7e15ef1dc4e3688c31872674c24b9b470b276 @alex alex committed Oct 21, 2009
Showing with 6 additions and 4 deletions.
  1. +6 −4 friends/managers.py
View
10 friends/managers.py
@@ -12,10 +12,12 @@
class FriendshipManager(models.Manager):
def friends_for_user(self, user):
friends = []
- for friendship in self.filter(from_user=user).select_related(depth=1):
- friends.append({"friend": friendship.to_user, "friendship": friendship})
- for friendship in self.filter(to_user=user).select_related(depth=1):
- friends.append({"friend": friendship.from_user, "friendship": friendship})
+ qs = self.filter(Q(from_user=user) | Q(to_user=user)).select_related(depth=1)
+ for friendship in qs:
+ if friendship.from_user == user:
+ friends.append({"friend": friendship.to_user, "friendship": friendship})
+ else:
+ friends.append({"friend": friendship.from_user, "friendship": friendship})
return friends
def are_friends(self, user1, user2):

0 comments on commit 00e7e15

Please sign in to comment.
Something went wrong with that request. Please try again.