【发布时间】: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