I am trying to make a table of contents for my queryset
in Django like this:
def get_toc(self):
toc = {}
qs = self.get_queryset()
idx = set()
for q in qs:
idx.add(q.title[0])
idx = list(idx)
idx.sort()
for i in idx:
toc[i] = []
for q in qs:
if q.title[0] == i:
toc[i].append(q)
return toc
But it has time complexity O(n^2)
. Is there a better way to do it?
UPDATE I meant glossary, not table of contents.
This doesn't look like a table of contents, but a glossary, where you map the first character of a term to a list of terms.
We can work with .groupby(…)
[python-doc] here:
from itertools import groupby
result = {
k: list(vs)
for k, vs in groupby(
self.get_queryset().order_by('title'), lambda x: x.title[0]
)
}