python - django 按日归档统计订单求解
PHP中文网
PHP中文网 2017-04-18 10:33:07
0
1
586

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

PHP中文网
PHP中文网

认证0级讲师

全部回覆(1)
刘奇

你的paid_in並不是資料庫字段,很明顯不能用在SQL語句中。兩個方法:

  1. 把符合時間段的orders實例取出來,用時間篩選。然後Sum(所有的order.pard_in)

  2. 資料庫層級Sum所有符合時段的訂單的paid_card, paid_cash, paid_gift

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板