[Answered ]-Regroup data from model in Django views

2👍

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)

-1👍

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!)

👤Ffion

Leave a comment