Django ORM 聚合税款总额

huangapple go评论47阅读模式
英文:

Django ORM aggregate tax sum

问题

taxes_sum = StoreAnalytics.objects.filter(store__user=self.request.user).annotate(
            taxes_sum=Sum(F("sales_sum") * F("tax") / 100)
        ).values_list('store_id__name', 'taxes_sum')
英文:

I have a Django project. There are Store model and Analytics model.
I want to calculate taxes sum for each store.
Is it possible to aggregate it by Django ORM in one request to DB? Without any loop by stores list?

I don't want smth like this:

for store in stores:
    taxes_sum = store.sales_sum*store.tax/100

I want smth like this:

taxes_sum = StoreAnalytics.objects.filter(store__user=self.request.user).aggregate(
            sales_sum=Sum(F("accruals_sum"))*Sum(F("tax"))/100)

but each store has its own tax percent (6%, 15%, 20%....)

class Store(models.Model):
    user = models.ForeignKey(User, on_delete=models.PROTECT)
    name = models.CharField(max_length=128, blank=True, default="", verbose_name="Name")
class StoreAnalytics(models.Model):

    store = models.ForeignKey(Store, on_delete=models.CASCADE, null=True, related_name="store_id")
    sales_sum = models.DecimalField(
        max_digits=10, decimal_places=2, default=Decimal(0), verbose_name="Sales")
    tax = models.IntegerField(
        default=6, validators=[MaxValueValidator(20), MinValueValidator(0)], verbose_name="Tax %"
    )

Is there any methods to calculate taxes sum?

答案1

得分: 1

可以这样做:

from django.db.models import (F, Sum)

StoreAnalytics.objects.filter().values("store__user_id").annotate(
    total_value=Sum((F("sales_sum") * F("tax")) / 100),
).order_by("store__user_id")
英文:

Yes we can do something like this:

from django.db.models import (F, Sum)

StoreAnalytics.objects.filter().values("store__user_id").annotate(
                    total_value=Sum((F("sales_sum")*F("tax"))/100),
                ).order_by("store__user_id")
   

huangapple
  • 本文由 发表于 2023年4月13日 14:30:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76002302.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定