假设这是我的模型:
class Item(models.Model):
user = models.ForeignKey(User, on_delete=models.DO_NOTHING)
price = models.DecimalField(max_digits=23, decimal_places=8, null=True, blank=True)
amount = models.DecimalField(max_digits=23, decimal_places=8)
我正在尝试获取所有记录,其金额之和将小于我给出的任何整数。 例如,从存在的 20 条记录中,返回前 5 条记录,其金额之和为 1000。就像拥有这些值:100,400,300,100,100。总和为 1000,因此它将它们作为查询集返回。 可以用循环来实现它,但我正在尝试用 django orm 来处理它。
谁能帮我解决这个问题吗?
最佳答案
有一种方法可以使用聚合函数 Sum 来做到这一点来自 Django 。
from django.db.models import Sum
amount_sum = Item.objects.filter(amount__lt=1000).aggregate(amount_sum=Sum("amount"))["amount_sum"]
但是,上面的 Django 查询将有一个等效的 SQL 查询:
SELECT SUM("app_Item"."amount") AS "amount_sum"
FROM "app_Item"
WHERE "app_Item"."amount" < 1000; args=(Decimal('1000'),)
关于python - 过滤查询其金额字段的总和大于或小于数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69372463/