首页 > 解决方案 > Django 子查询,注释。有什么方法可以连接三个表进行查询以查找 django 中某个字段的总和(查询集 api)?

问题描述

我是 django 的完整初学者。我被这个问题困住了,似乎找不到正确查询它的解决方案。(TT)

django ver : 1.11 python ver : 2.7 

假设我们有 3 个模型:

class Coupon(models.Model):
    pass

class CouponApplication(models.Model):
    """
    Track application of a coupon.
    """
    coupon = models.ForeignKey(Coupon, related_name="applications",verbose_name=("Coupon"))
    order = models.ForeignKey(Order, verbose_name=("Order")related_name='order_coupon_applications')

class Order(models.Model):

    user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='user_order', verbose_name="Customer")
    order_date = models.DateTimeField(verbose_name='Order Date and Time')
    shop = models.ForeignKey(Location, null=True, on_delete=models.SET_NULL)


class OrderItem(models.Model):
    order = models.ForeignKey(Order, related_name='order_items')
    order_type = models.CharField('Type', choices=ORDER_ITEM_TYPE, default=INVENTORY)
    buy_get_discount = models.DecimalField(_('Buy & Get Discount'))
    sub_total = models.DecimalField(_('Sub Total'), max_digits=18, decimal_places=2)

现在对于每张优惠券,我需要找到使用它销售的产品的总销售额。我发现编写相同的查询非常困难,因为我需要将订单项小计的总和注释到每个优惠券对象,我想这需要加入优惠券应用程序、订单项和订单表。

到目前为止,我已经写了这么多:

buy_gets_gross_sales = OrderItem.objects.filter(order_type=OrderItem.INVENTORY,
                                                        buy_get_discount__gt=0,
                                                        order_id__in=CouponApplication.objects.filter(coupon=OuterRef('pk'),
                                                            ).values('order')
                                                        ).values('order_type')
        gross_sales = buy_gets_gross_sales.annotate(gross=Sum('sub_total')).values('gross')
gross_Sales_report = Coupon.objects.annotate(
            total_gross_sales =Round(Coalesce(Subquery(gross_sales, output_field=models.DecimalField()), Value(0))) ,)

我知道这行不通,但我需要这种东西。它已经抛出一些错误,说内部查询需要在子查询或其他东西中使用。我需要用优惠券对象注释聚合值。

我也在下面添加了原始 sql 查询:

'(select coalesce(sum(sub_total),0) from order_orderitem'
            ' where order_type=%(order_type)s and buy_get_discount > %(discount)s'
            'and order_id in (select distinct(order_id) from coupon_couponapplication where coupon_id=t1.id '
            '{0}'
            'and date_created between %(start)s and %(end)s'  # comment this line to remove date filter
            ')) '

这里 t1 是优惠券模型。

帮助,我很确定可以为此编写 django 查询,但正如我所说,我无法弄清楚。

请帮助我找到解决方案,在此先感谢。<3

标签: pythondjangoormdjango-queryset

解决方案


推荐阅读