【问题标题】:How can I convert Inner Join and Group By to Django ORM?如何将 Inner Join 和 Group By 转换为 Django ORM?
【发布时间】: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


    【解决方案1】:

    我解决了! How to combine select_related() and value()? (2016)

    有趣的事实;我猜我的问题与 ORM 无关。我不知道我可以通过将其添加到我在这篇文章中分享的最后一个代码中的.values('student__name', 'student__surname') 来访问学生对象的属性。

    这段代码;

     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'))
    

    到此代码;

    LendedBook.objects.select_related('User_student')
    .values('student_id', 'student__name', 'student__surname')
    .filter(did_read=True, return_date__month=(datetime.datetime.now().month))
    .annotate(count=Count('student_id'))
    

    顺便说一句,删除.select_related('User_student')不影响结果。

    所以,使用 _ 解决了我的问题!

    【讨论】:

      猜你喜欢
      • 2016-09-13
      • 2021-10-08
      • 2015-08-21
      • 2021-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多