Create lists / reports with embedded resumes in Django

I am trying to write a presentation that will generate a report that displays all the elements in my inventory system, and provide a summary at a certain point. By the way, this report is just an HTML template.

In my case, each item is part of the order. An order can have several elements, and I want them to display a CV based on SUM after the end of each order.

Thus, the report view is as follows:

Order #25        <Qty> <Qty Sold> <Cost> <Cost Value>
Some Item          2       1       29.99    29.99
Another Item       4       0       10.00    40.00
<Subtotal Line>    6       1       39.99    69.99
Order #26        <Qty> <Qty Sold> <Cost> <Cost Value>
... Etc, you get the point

Now I’m quite capable of displaying all the values ​​and already have a report showing all the elements, but I have no idea how to place the subtopics marked in the report without making alot of queries. The Quantity, Qty Sold, and Cost fields are part of the Item model, and Cost Value is just a simple function of the model.

Any help would be greatly appreciated. Thank you in advance: -)

+5
source share
3 answers

Interim results SELECT SUM(qty) GROUP BY order_number.

They are completely separate from the request to get the details.

The results of the two queries should alternate. A good way to do this is to create each order as a tuple ( list_of_details, appropriate summary ).

Then the display is easy

{% for order in orderList %}
    {% for line in order.0 %}
        {{ line }}
    {% endfor %}
    {{ order.1 }}
{% endfor %}

The hard part alternates between two requests.

details = Line.objects.all()
ddict = defaultdict( list )
for d in details:
    ddict[d.order_number].append(d)

interleaved= []
subtotals = ... Django query to get subtotals ... 
for s in subtotals:
    interleaved.append( ( ddict[s.order], s.totals ) )

interleaved .

+3

Python Django.

- Model , , . , sub-total -.

+1

, - , , python:

from itertools import groupby
items = OrderItem.objects.select_related('order').order_by('order').all() # order_by is essential
items_by_order = dict(groupby(items, lambda x: x.order))
for order, items in items_by_order:
    items_by_order[order]['subtotals'] = ... # calculate subtotals for all needed fields

separeate SQL- , WHERE . agregate, , .

+1
source

All Articles