Lleims
Lleims

Reputation: 1353

Regroup data from model in Django views

I have a model with data like the following:

Name    Value    Date
pop1    15       2021-01-19
pup1    2        2021-01-18
pep1    25       2021-01-18
pop2    9        2021-01-17
pap1    1        2021-01-16
pep2    26       2021-01-16
pep3    4        2021-01-16

If i do data = myModel.objects.all() I obtain all the data in the normal structure, but what I want is obtain it grouped by date. Can this goal be achieved directly?

I ask this because I know how to filter using myModel.objects.filter() or order the data using myModel.objects.order_by(). Then, exists something like myModel.objects.regroup('date')?

EDIT:

The desired output is something like:

date:2021-01-19 >> [[name:pop1, value:15]]
date:2021-01-19 >> [[name:pup1, value:2],[name:pep1, value:25]]
date:2021-01-17 >> [[name:pop2, value:9]]
date:2021-01-16 >> [[name:pap1, value:1],[name:pep2, value:26],[name:pep3, value:4]]

Basically an object with the data regrouped by date.

Thank you very much.

Upvotes: 1

Views: 208

Answers (2)

Belhadjer Samir
Belhadjer Samir

Reputation: 1659

you can use this :

data=myModel.objects.all()
new_data={}
for e in data :
  
  if e.value('date') not in new_data :
    new_data[e.value('date')]=[e]
  else :
    new_data[e.value('date')].append(e)
print(new_data)

Upvotes: 2

Ffion
Ffion

Reputation: 559

Based on the accepted answer to this question and the accepted answer to this question you should be able to change your view as follows:

dates_list = MyModel.objects.values_list(
    'date', flat=True
).distinct()

group_by_date = {}
for date in dates_list:
    group_by_date[date] = MyModel.objects.filter(date=date)

then in your template:

{% for date, items in group_by_date %}
    date: {{ date }} >>

    {% for item in items %}
      [ name: {{ item.name }}, value: {{ item.value }} ]
    {% endfor %}

    <br />
{% endfor %

(Obviously you'll want to use more HTML tags to format the output in a more pleasing way!)

Upvotes: -1

Related Questions