python django获取某个角色的某个数据和——例如:获取所有订单的应付金额总和

model关系如下:

class Order(models.Model):
    '''订单'''
    product = models.ForeignKey('Product', on_delete=models.SET_NULL, blank=True, null=True, verbose_name="产品")

    no = models.CharField(max_length=50, blank=True, null=True, verbose_name='订单编号', db_index=True)
    total_money = models.BigIntegerField(default=0, blank=True, null=True, verbose_name='订单总金额(分)')
    settlement_money = models.BigIntegerField(default=0, blank=True, null=True, verbose_name='应付现金金额(分)')
    pay_money = models.BigIntegerField(default=0, blank=True, null=True, verbose_name='实付现金金额(分)')

    create_time = models.DateTimeField(auto_now_add=True, blank=True, null=True, verbose_name='创建时间')

获取指定时间段内所有订单的应付金额总和

方法一:使用aggregate()
from django.db.models import Q
from django.db.models import Sum
from . import models

#方法一:
def get_count(request):
    lookups = Q()
    if request.GET.get('start_time'):
        lookups = lookups & Q(create_time__gte=request.GET.get('start_time')
    if request.GET.get('end_time')
        lookups = lookups & Q(create_time__lte=request.GET.get('end_time')

    total_order_money = models.Order.objects.filter(lookups).aggregate(total_settlement_money=Sum('settlement_money'))['total_settlement_money']
方法二:使用sum()

你可能感兴趣的:(python,django,数据库)