dhooonk
dhooonk

Reputation: 2625

How to print out and use list variable (using groupby)

def moneybook_detail(request, pk):
    moneybook = moneybook_models.Moneybook.objects.get(pk=pk)
    moneylogs = moneybook.moneylog_set.all()

    def extract_pay_day(moneylogs):
        return moneylogs.pay_day.date()

    same_day_pays = moneylogs.order_by("pay_day")
    for pay_day, group in groupby(same_day_pays, key=extract_pay_day):  
        print(pay_day, list(group))

I don't fully understand the looping in this line. I'm just following this post on stackoverflow.

then I get the below query.

2020-01-09 [<Moneylog: Moneylog object (4)>]
2020-01-12 [<Moneylog: Moneylog object (1)>, <Moneylog: Moneylog object (2)>, <Moneylog: Moneylog object (3)>, <Moneylog: Moneylog object (5)>, <Moneylog: Moneylog object (6)>]

How can I use this query in html? which variable do I have to use? Like:

{{same_day_pay.pay_day}}
{% for same_day_pay in same_day_pays %}
    {{same_day_pay.memo}} / {{same_day_pay.price}}
{% endfor% }

-> result

**2019.01.03**
pay1 / 120
pay2 / 200

**2019.01.02**
pay0 / 100 

Upvotes: 0

Views: 52

Answers (1)

Chris
Chris

Reputation: 2212

You could create a nested list in your view and use it in your template, e.g. your view:

    def moneybook_detail(request, pk):
        moneybook = moneybook_models.Moneybook.objects.get(pk=pk)
        moneylogs = moneybook.moneylog_set.all()

        def extract_pay_day(moneylogs):
            return moneylogs.pay_day.date()

        same_day_pays = moneylogs.order_by("pay_day")
        sd_list = []
        for pay_day, group in groupby(same_day_pays, key=extract_pay_day):  
            sd_list.append((pay_day, list(group)))

        return render(request, 'moneylog.html', {'samedaypays': sd_list})

and in the template

{% for sd in samedaypays %}
    <p>** {{ sd.0 }} **</p>
    {% for o in sd.1 %}
        <p>{{ o.memo }} / {{ o.price }}</p>
    {% endfor %}
{% endfor %}

Just for the sake of completeness: There is also a django template tag called regroup allowing you to do the same in your template as described here

Upvotes: 1

Related Questions