E
E
Evgeny Zhukov2021-04-08 08:13:06
Django
Evgeny Zhukov, 2021-04-08 08:13:06

How to form the output of elements alphabetically with grouping?

Good afternoon, I apologize if my question is too stupid, but here is my task:
I have a model with books, for example, 2000 objects are loaded there. I need to form a certain catalog of elements on the page alphabetically grouped by the first letter:
A:
Name
Name
Name
B:
Name
Name
Name C
:
Name
Name
Name

How to implement this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
WStanley, 2021-04-08
@WStanley

For example, with a raw request, you can get this
https://docs.djangoproject.com/en/3.1/topics/db/sq...

books = Books.objects.raw(
    """SELECT id, name FROM            
    (
        SELECT DISTINCT NULL AS id, LEFT(name, 1) AS name FROM Books
        UNION ALL
        SELECT DISTINCT  id, name FROM  Books AS Books1
        ORDER BY name
    ) AS t1
    ORDER BY name""")

for book in books:
    print(book.id)
    print(book.name)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question