Answer the question
In order to leave comments, you need to log in
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
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 questionAsk a Question
731 491 924 answers to any question