1

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.