Marco
Marco

Reputation: 335

Advanced database query in Django

I have a table(model) in my database like this:

Name|avarage|evaluation

Marco| 9.6 | 1

Marco| 9.3 | 2

Kevin | 8.8 | 1

Kevin | 9.4 | 2

So I need to get this data to show a table at the template in this way:

Name | eval1 | eval2

Marco | 9.6 | 9.3

Kevin | 8.8 | 9.4

How can I make the query in my view?

Upvotes: 1

Views: 127

Answers (1)

pawroman
pawroman

Reputation: 1300

There is no easy way to do this using only ORM. Try using itertools.groupby:

from itertools import groupby

results = ModelCls.objects.order_by("name")

grouped = groupby(results, lambda r: r.name)

You now have your models grouped by name:

for name, objects in grouped:
    # process model objects in each group
    for obj in objects:
        # do something with each object

Passing the groupby object to the template should work just fine, but be aware that it's a generator and will be exhausted after you iterate over it.

Upvotes: 1

Related Questions