db optimizations
[wolnelektury.git] / src / wolnelektury / views.py
index 49f7b24..1a6738b 100644 (file)
@@ -25,20 +25,20 @@ from ssify import ssi_included
 def main_page(request):
     ctx = {
         'last_published': Book.objects.exclude(cover_thumb='').filter(parent=None).order_by('-created_at')[:6],
+        'theme_books': []
     }
 
-    for category in ('author', 'epoch', 'genre', 'kind'):
-        try:
-            ctx[category] = Tag.objects.filter(category=category).order_by('?')[:1][0]
-        except IndexError:
-            pass
+    for category in ('author', 'epoch', 'genre', 'kind'):
+        try:
+            ctx[category] = Tag.objects.filter(category=category).order_by('?')[:1][0]
+        except IndexError:
+            pass
 
     # FIXME: find this theme and books properly.
-    ctx['theme_books'] = []
-    if Fragment.objects.count():
+    if Fragment.objects.exists():
         while True:
             ctx['theme'] = Tag.objects.filter(category='theme').order_by('?')[:1][0]
-            tf = Fragment.tagged.with_any([ctx['theme']]).order_by('?')[:100]
+            tf = Fragment.tagged.with_any([ctx['theme']]).select_related('book').order_by('?')[:100]
             if not tf:
                 continue
             ctx['theme_fragment'] = tf[0]