您的位置:首页技术文章
文章详情页

python - django 按日归档统计订单求解

【字号: 日期:2022-08-02 14:48:12浏览:14作者:猪猪

问题描述

models.py:订单数据模型

class Order(models.Model): date = models.DateTimeField(default=timezone.now) paid_card = models.PositiveIntegerField(blank=True, null=True) paid_cash = models.PositiveIntegerField(blank=True, null=True) paid_gift = models.PositiveIntegerField(blank=True, null=True)statur = models.CharField() @property # 实收金额(paid_in) = paid_card + paid_cash + paid_gift def paid_in(self):return sum(filter(None, [self.paid_card, self.paid_cash, self.paid_gift]))

views.py: 按日归档统计每天的订单数、订单总额

def wx_archive(request): orders = Order.objects.filter(status=’closed’).annotate(day=TruncDay(’start_time’)).values(’day’).annotate(count=Count(’id’), total=Sum(’paid_in’)).values(’day’, ’count’, ’total’).order_by(’day’) return render(request, ’orders/archive.html’, {’orders’: orders})

运行后报错,提示

FieldError at /orders/archive/Cannot resolve keyword ’paid_in’ into field. Choices are: count, day, id, paid_card, paid_cash, paid_gift, status

请问,我该如何统计每日的总 paid_in?

问题解答

回答1:

你的paid_in并不是数据库字段,很明显不能用在SQL语句中。两个方法:

把符合时间段的orders实例取出来,用时间筛选。然后Sum(所有的order.pard_in)

数据库层面Sum所有符合时间段的订单的paid_card, paid_cash, paid_gift

标签: Python 编程
相关文章: