summaryrefslogtreecommitdiffstats
path: root/todolists/utils.py
blob: 03c4793111fe41264942e55377d9bdb175264d19 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
from django.db import connections, router
from django.db.models import Count

from main.models import Todolist, TodolistPkg


def todo_counts():
    sql = """
SELECT list_id, count(*), sum(CASE WHEN complete THEN 1 ELSE 0 END)
    FROM todolist_pkgs
    GROUP BY list_id
    """
    database = router.db_for_write(TodolistPkg)
    connection = connections[database]
    cursor = connection.cursor()
    cursor.execute(sql)
    results = cursor.fetchall()
    return {row[0]: (row[1], row[2]) for row in results}


def get_annotated_todolists(incomplete_only=False):
    lists = Todolist.objects.all().select_related(
            'creator').order_by('-date_added')
    lookup = todo_counts()

    # tag each list with package counts
    for todolist in lists:
        counts = lookup.get(todolist.id, (0, 0))
        todolist.pkg_count = counts[0]
        todolist.complete_count = counts[1]
        todolist.incomplete_count = counts[0] - counts[1]

    if incomplete_only:
        lists = [l for l in lists if l.incomplete_count > 0]

    return lists

# vim: set ts=4 sw=4 et: