python - Django 注释 sum 子查询

标签 python django

如何对子查询的字段(使用 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',
    )
)

关于python - Django 注释 sum 子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57977925/

相关文章:

Django过滤器不起作用

python - 如何使用 jsonpath-ng 算法?

python - Numpy 在行上循环追加二维数组

python - boost python : tie lifetime of argument to returned value using return_internal_reference

python - 如何在映射 Django 模型时使用多个外键

python - Django:如何在相关字段的相关字段上排序

python - Django REST Framework 序列化程序 - 访问现有的外键

python - Python Decimal(32) 在 Swift 中相当于什么?

python - pickle python 类实例

python - Django 模板中有两种不同的形式