id – line_id – line_text
1 – 1 – text
2 – 1 – text
3 – 1 – text
4 – 2 – text
5 – 2 – text
6 – 3 – text
7 – 3 – text
Is it possible to use aggregation or some other method to group by line_id and end up with three results rather than the seven rows? So basically break the above into three result sets like;
You could query all the relevant items in one query, then group them in memory with itertools.groupby.
from itertools import groupby
from operator import attrgetter
for category_id, lines in groupby(Line.objects.order_by('category_id'), key=attrgetter('category_id')):
...