Django ORM 聚合税款总额

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

Django ORM aggregate tax sum

问题

  1. taxes_sum = StoreAnalytics.objects.filter(store__user=self.request.user).annotate(
  2. taxes_sum=Sum(F("sales_sum") * F("tax") / 100)
  3. ).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:

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

I want smth like this:

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

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

  1. class Store(models.Model):
  2. user = models.ForeignKey(User, on_delete=models.PROTECT)
  3. name = models.CharField(max_length=128, blank=True, default="", verbose_name="Name")
  1. class StoreAnalytics(models.Model):
  2. store = models.ForeignKey(Store, on_delete=models.CASCADE, null=True, related_name="store_id")
  3. sales_sum = models.DecimalField(
  4. max_digits=10, decimal_places=2, default=Decimal(0), verbose_name="Sales")
  5. tax = models.IntegerField(
  6. default=6, validators=[MaxValueValidator(20), MinValueValidator(0)], verbose_name="Tax %"
  7. )

Is there any methods to calculate taxes sum?

答案1

得分: 1

可以这样做:

  1. from django.db.models import (F, Sum)
  2. StoreAnalytics.objects.filter().values("store__user_id").annotate(
  3. total_value=Sum((F("sales_sum") * F("tax")) / 100),
  4. ).order_by("store__user_id")
英文:

Yes we can do something like this:

  1. from django.db.models import (F, Sum)
  2. StoreAnalytics.objects.filter().values("store__user_id").annotate(
  3. total_value=Sum((F("sales_sum")*F("tax"))/100),
  4. ).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:

确定