Django ORM - 向结果添加行,直到 SUM('column') 达到给定的数字

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

我有一个使用 Django ORM 创建的模型 -

class Orders:
    units = models.IntegerField(null=False, blank=False)
    sell_price_per_unit = models.FloatField(null=True, blank=True)
    created_by = models.ForeignKey(User, on_delete=models.PROTECT, null=False, blank=False)
    order_status = models.ForeignKey(OrderStatus, on_delete=models.PROTECT, null=False, blank=False)
    property = models.ForeignKey(Property, on_delete=models.PROTECT, null=False, blank=False)
    order_type = models.ForeignKey(Property, on_delete=models.PROTECT, null=False, blank=False)
    ...
    ...

我想向 select_for_update() 写入查询,并且应该 select 编辑行,直到 Sum('sell_price_per_unit') 达到给定的数字。此外,我必须应用某些过滤器并根据条件排除某些行。 filter()exclude() 非常简单,所以我已经处理了它,但我不知道如何 select 行,直到 Sum('sell_price_per_unit') 达到给定的数字。

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")
        )

有可能实现吗?

此处the SQL类似问题的解决方案。我不确定是否可以用 DjangoORM 编写它。

所以,您可以使用rawSQL查询记录。

但是如果你有合理数量的记录,你可以简单地在应用程序端过滤它

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
...