如何对子查询的字段求和(使用OuterRef)并在外部模型上对其进行注释?你知道吗
注意,我有一个公共的my_special_queryset_annotator
,它通过添加一些注释来改变queryset。。。所以我不想直接使用Sum('books__sections__page')
假设以下模型
class Library(models.Model):
votes=models.IntegerField()
class Book(models.Model):
library=models.ForiegnKey(Library)
class Section(models.Model):
book=models.ForiegnKey(Book)
pages=models.IntegerField()
# this works, but when want to use `my_special_queryset_annotator`
# we could not do this simple annotation
Library.annotate(
all_pages=Sum('books__sections__pages'),
)
# when want to sum on a Subquery, its must constructed like below but it dont work
Library.objects.annotate(
all_pages=SUM( # <-- problem
Subquery(
my_special_queryset_annotator(
Section.objects.filter(book__libraray_id=OuterRef('id'))
).values('altered_pages')
)
)
)
解决这个问题的一种尝试是创建如下内容,但我无法配置如何不将
sum_field
参数传递给它,而只在给定的queryset上使用.values(sum_field)
相关问题 更多 >
编程相关推荐