Django ORM查询或原始SQL查询

时间:2017-12-01 06:15:53

标签: sql django django-models subquery django-queryset

我需要进行查询,在那里我可以显示客户订购的衣服总量,结果应该是这样的:

Client_1 | Cloth_Type_X_SUM | Cloth_Type_Y_SUM | Cloth_Type_Z_SUM | SUM_ALL Client_2 | Cloth_Type_X_SUM | Cloth_Type_Y_SUM | Cloth_Type_Z_SUM | SUM_ALL Client_3 | Cloth_Type_X_SUM | Cloth_Type_Y_SUM | Cloth_Type_Z_SUM | SUM_ALL

models.py

class Cloth(models.Model):
    description = models.CharField(max_length=30)
    type = models.CharField(max_length=2)

class Order(models.Model):
    client = models.ForeignKey(Client, on_delete=models.CASCADE)
    date = models.DateTimeField(auto_now_add=True)

class Order_Detail(models.Model):
    order = models.ForeignKey(Order, on_delete=models.CASCADE)
    cloth = models.ForeignKey(Cloth, on_delete=models.CASCADE)
    weight = models.FloatField()

我最接近的是:

Order_Detail.objects.values('order__client__name','cloth__type').annotate(Sum('weight'))

这个问题是它将为每种布料类型检索一个对象:

Client_1 | Cloth_Type_X | SUM_X
Client_1 | Cloth_Type_Y | SUM_Y
Client_1 | Cloth_Type_Z | SUM_Z
Client_2 | Cloth_Type_X | SUM_X
Client_2 | Cloth_Type_Y | SUM_Y
Client_2 | Cloth_Type_Z | SUM_Z
Client_3 | Cloth_Type_X | SUM_X
Client_3 | Cloth_Type_Y | SUM_Y
Client_3 | Cloth_Type_Z | SUM_Z

有没有更好的方法?

2 个答案:

答案 0 :(得分:1)

您可以将Conditional Expressions用于此目的

Order_Detail.objects.values('order__client').annotate(
   cloth_type_x_sum = Sum(Case(When(cloth__type=X, then='weight'))), 
   cloth_type_y_sum = Sum(Case(When(cloth__type=Y, then='weight'))),
   cloth_type_z_sum = Sum(Case(When(cloth__type=Z, then='weight'))),
).order_by('order__client')

答案 1 :(得分:0)

from django.db.models import Sum
Order_Detail.objects.values('cloth').annotate(cloth_weight=Sum('weight'))

这将按照布料类型进行分组。

Order_Detail.objects.values('order__client').annotate(cloth_weight=Sum('weight'))

这将由客户提供。