I want to change this raw SQL to Django ORM but I couldn't manage to convert.
most_read_students = LendedBook.objects.raw('
SELECT student_id as id, name, surname, COUNT(*) as count
FROM "Book_lendedbook"
INNER JOIN User_student on Book_lendedbook.student_id=User_student.id
where did_read=1
group by student_id
order by count DESC
LIMIT 5')`
I tried this and I get close result.But unfortunately, I couldn't do what I want. Because I want to join this table with another table.
most_read_students = LendedBook.objects.values('student_id')
.filter(did_read=True, return_date__month=(datetime.datetime.now().month))
.annotate(count=Count('student_id'))
When I use select_related with "User_student" table like this;
most_read_students = LendedBook.objects.select_related('User_student')
.values('student_id', 'name', 'surname')
.filter(did_read=True, return_date__month=(datetime.datetime.now().month))
.annotate(count=Count('student_id'))
It throws an error like Cannot resolve keyword 'name' into field. Choices are: book, book_id, did_read, id, is_returned, lend_date, return_date, student, student_id
But I should be able to get student properties like name and surname when I join "User_student" table.
Thank you for your help!