【发布时间】:2021-07-21 16:45:32
【问题描述】:
我想将此原始 SQL 更改为 Django ORM,但无法转换。
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')`
我试过这个,我得到了接近的结果。但不幸的是,我不能做我想做的事。因为我想把这个表和另一个表连接起来。
most_read_students = LendedBook.objects.values('student_id')
.filter(did_read=True, return_date__month=(datetime.datetime.now().month))
.annotate(count=Count('student_id'))
当我像这样将 select_related 与“User_student”表一起使用时;
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'))
它会抛出类似Cannot resolve keyword 'name' into field. Choices are: book, book_id, did_read, id, is_returned, lend_date, return_date, student, student_id 的错误
但是当我加入“User_student”表时,我应该能够获得姓名和姓氏等学生属性。
感谢您的帮助!
【问题讨论】:
标签: python django django-orm