[Answered ]-Django ORM – add rows to the result until the SUM('column') reaches to a given number

1👍

Here the SQL solution of similar problem. I’m not sure, if it’s possible to write it in DjangoORM.

So, you can use rawSQL to query records.

But if you have reasonable amount of records you can simply filter it on application side

queryset = (
    Orders.objects.select_for_update()
    .exclude(created_by=created_by)
    .values(
        "id",
        "property",
        "units",
        "created_by",
        "sell_price_per_unit",
        "order_status",
    )
    .filter(
        property=order_obj.property,
        order_type__name=SELL,
        order_status__in=[PARTIALLY_COMPLETED[1], OPEN[1]],
        sell_price_per_unit__lte=order_price,
    )
    .order_by("sell_price_per_unit", "created_at")
)

current_sum = 0

orders = []
for order in queryset:
    current_sum += order.sell_price_per_unit
    if current_sum > threshold:
        break

# Do stuff with orders
...

Leave a comment