0
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 
David Buck
  • 3,752
  • 35
  • 31
  • 35
dhooonk
  • 2,115
  • 3
  • 11
  • 17

1 Answers1

1

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

Chris
  • 2,162
  • 1
  • 6
  • 17
  • thansk for reply. but it occur >> same_day_list.append = (pay_day, list(group)) AttributeError: 'list' object attribute 'append' is read-only error.. – dhooonk Jan 18 '20 at 13:03
  • Are you sure you read my code correctly? I created a new list called ```sd_list = []```. I am not appending anything to an existing query or something. – Chris Jan 18 '20 at 13:07
  • yes unfortunately, i also created new list called same_day_list (just change the name.) and it happend. – dhooonk Jan 18 '20 at 13:11
  • 1
    Sorry, just spoted you have a typo: It is not ```same_day_list.append = (pay_day, list(group))``` but ```same_day_list.append((pay_day, list(group)))``` – Chris Jan 18 '20 at 13:15