我有两个模型,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')
)
)
我尝试将此解决方案与Willem 解决的较早帖子结合起来引用,但使用 distinct 似乎会导致上面引用的 NotImplementedError 。我相信也可能有一个使用 Count( , distinct=True) 的解决方案,但除非我可以在 date__date 上区分,否则它不会有帮助,因为我只是想找到发生任何数量的交易的日期。
非常感谢您的宝贵时间。