Commits

Anonymous committed 0b1fda9

optimize query

  • Participants
  • Parent commits 8a9c601

Comments (0)

Files changed (1)

newsmeme/models.py

         the user or c) posts authored by friends
         """
 
-        if user is None:
-            return self.filter(Post.access==Post.PUBLIC)
-
-        if user.is_moderator:
+        if user and user.is_moderator:
             return self
 
-        return self.filter(db.or_(Post.access==Post.PUBLIC,
-                                  Post.author_id==user.id,
-                                  db.and_(Post.access==Post.FRIENDS, 
-                                          Post.author_id.in_(user.friends))))
+        criteria = [Post.access==Post.PUBLIC]
 
+        if user:
+            criteria.append(Post.author_id==user.id)
+            if user.friends:
+                criteria.append(db.and_(Post.access==Post.FRIENDS,
+                                        Post.author_id.in_(user.friends)))
+        
+        return self.filter(reduce(db.or_, criteria))
 
     def search(self, keywords):