python - Django 注释 sum 子查询
问题描述
如何对子查询的字段(使用 OuterRef )求和并在外部模型上对其进行注释?
请注意,我有一个共同点my_special_queryset_annotator
,通过添加一些注释来改变查询集,......所以我不想直接使用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
参数传递给它并仅.values(sum_field)
在给定的查询集上使用
class SumSubquery(Subquery):
template = "(SELECT SUM(%(sum_field)s) FROM (%(subquery)s) _sum)"
output_field = models.DecimalField()
def __init__(self, queryset, output_field=None, *, sum_field, **extra):
extra['sum_field'] = sum_field
super(SumSubquery, self).__init__(queryset, output_field, **extra)
# and use like below
Library.objects.annotate(
all_pages=SumSubquery(
my_special_queryset_annotator(
Section.objects.filter(book__libraray_id=OuterRef('id'))
),
sum_field='altered_pages',
)
)
推荐阅读
- c# - 在 Linq where 子句中动态反序列化 Json
- maven - 在多模块项目中只执行一次插件目标
- html - 如何使用 getBoundingClientRect() 在 Angular 的 html 页面中根据 div 部分的位置执行一些操作
- reactjs - React JS - 如何防止重复提交和触发搜索调用表单
- python - 减少ParallelMapDataset的维度
- azure - Kusto 声明虚拟整数并保存其更新状态
- ssh - SSH 远程隧道端口
- reactjs - 使用 react-rater,如何将评分值发送到数据库,并计算平均评分
- c# - 在 IIS (10.0.17763.1) 上托管 .net5.0 核心 Web api 时出现问题
- python - 如何用条件替换熊猫列值?