【发布时间】:2021-09-26 16:46:13
【问题描述】:
我有两个模型,RetailLocation 和 Transaction,它们分别共享一对多的关系。我试图注释一个零售位置有任意数量的交易的总天数(计数)。这样做时,我将 Transaction.date 字段过滤为 Date 而不是 Datetime,并尝试选择 DISTINCT 日期,但遇到错误“NotImplementedError: annotate() + distinct(fields) 未实现。 ”
型号
class RetailLocation(models.Model):
name = models.CharField(max_length=200, null=True)
class Transaction(models.Model):
date = models.DateTimeField(null=True)
r_loc = models.ForeignKey(RetailLocation, null=True, on_delete=models.SET_NULL)
尝试的代码
test = RetailLocation.objects.annotate(
days_operating=Subquery(
Transaction.objects.filter(r_loc=OuterRef("pk"))
.distinct('date__date')
.annotate(count=Count('pk'))
.values('count')
)
)
I tried to reference this solution 与 an earlier post solved by Willem 结合使用,但使用 distinct 似乎会导致上面提到的 NotImplementedError。我相信也可能有一个使用 Count( , distinct=True) 的解决方案,但除非我可以在 date__date 上区分,否则它无济于事,因为我只是想找出发生了任意数量的交易的日期。
非常感谢您的宝贵时间。
【问题讨论】:
标签: django subquery distinct primary-key django-annotate