[Answered ]-Django – filter queryset until Sum is reached

1👍

This might help annotating accumuated_sum:

from django.db.models import Subquery, IntegerField

class SQSum(Subquery):
    output_field = IntegerField()
    template = "(SELECT sum(outcome) from (%(subquery)s) _sum)"

accumulated_subquery = SQSum(
    Roll.objects.filter(
        pk__lte=OuterRef('pk')
    ).values("outcome")
)

Roll.objects.annotate(accumulated_sum=accumulated_subquery).filter(accumulated_sum__gte=amount)

Leave a comment