【问题标题】:Count rows of a subquery in Django 1.11在 Django 1.11 中计算子查询的行数
【发布时间】:2018-02-19 13:14:09
【问题描述】:

我有几个模型

class Order(models.Model):
    user = models.ForeignKey(User)

class Lot(models.Model):
    order = models.ForeignKey(Order)
    buyer = models.ForeignKey(User)

我要做的是用给定用户对同一卖家的多次购买来注释Lot 对象。 (没看错,Order.user真的是卖家)。比如“你最近从这个用户那里买了 4 件商品”。

我得到的最接近的是

recent_sold_lots = Lot.objects.filter(
    order__user_id=OuterRef('order__user_id'),
    status=Lot.STATUS_SOLD,
    buyer_id=self.user_id,
    date_sold__gte=now() - timedelta(hours=24),
)

qs = Lot.objects.filter(
    status=Lot.STATUS_READY,
    date_ready__lte=now() - timedelta(seconds=self.lag)
).annotate(same_user_recent_buys=Count(Subquery(recent_sold_lots.values('id'))))

但是当recent_sold_lots 计数大于一时它会失败:用作表达式的子查询返回多于一行。

.annotate(same_user_recent_buys=Subquery(recent_sold_lots.aggregate(Count('id'))) 似乎也不起作用:此查询集包含对外部查询的引用,并且只能在子查询中使用。

.annotate(same_user_recent_buys=Subquery(recent_sold_lots.annotate(c=Count('id')).values('c')) 给我表达式包含混合类型。您必须设置 output_field。。如果我将output_field=models.IntegerField() 添加到子查询调用中,它会抛出由用作表达式的子查询返回的多行

我被这个卡住了。我觉得我已经接近解决方案了,但是我在这里缺少什么?

【问题讨论】:

    标签: python django django-orm


    【解决方案1】:

    您在问题中定义的模型未正确反映您正在执行的查询。在任何情况下,我都会使用模型作为查询的参考。

    from django.db.models import Count
    
    user_id = 123 # my user id and also the buyer
    buyer = User.objects.get(pk=user_id)
    
    Lot.objects.filter(buyer=buyer).values('order__user').annotate(unique_seller_order_count=Count('id'))
    

    查询的作用是:

    1. 将批次对象过滤为您已购买的对象
    2. 将退回的批次分组到创建订单的用户中
    3. 注释/计算每个组的响应

    【讨论】:

    • 当模型有关系时,此解决方案有效。如果您试图依靠没有关系的模型,这是行不通的。
    猜你喜欢
    • 2021-04-12
    • 2017-07-21
    • 2011-07-18
    • 1970-01-01
    • 2018-11-22
    • 1970-01-01
    • 2016-11-14
    • 1970-01-01
    • 2015-11-17
    相关资源
    最近更新 更多