英文:
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")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论