我已经对 Student 对象进行了注释,使其具有两个新字段-> project_count 和 member_count,如下所示:
top_students = Student.objects.annotate(project_count= Count('project'), member_count = Count('member_student'))
我现在想在数据库级别执行这两个值的总和。即返回类似:
total_count = project_count + member_count
我试过像这样使用 .extra() :
top_students = Student.objects.annotate(project_count= Count('project'), member_count = Count('member_student')).extra(
select = {'total_count': 'project_count + member_count'},
order_by = ('total_count', )
)
但它显示一个错误:OperationalError: (1054, "Unknown column 'project_count' in 'field list'")
我应该编写原始 SQL 还是有其他方法可以做到这一点: