注释'id'与模型上的字段冲突



在注释中,我试图获得is_healthyTrue的查询计数,但我得到一个错误The annotation 'id' conflicts with a field on the model.有解这个的方法吗?为什么会这样,我怎么解决呢?

DeviceHealthHistory.objects.filter(**filter_data).values(
id = F('id'),
).annotate(
healthy_count=Count('id', filter=Q(is_healthy=True)),
)

如果您只是在寻找计数,那么您使用count函数查询集:

DeviceHealthHistory.objects.filter(**filter_data).filter(is_healthy=True).count()

获取其他字段和计数。

DeviceHealthHistory.objects.filter(**filter_data).values(
'other_field1'
).annotate(
healthy_count=Count('id', filter=Q(is_healthy=True)),
)

你应该用:

DeviceHealthHistory.objects.filter(**filter_data, is_healthy=True).count()

这将过滤**filter_data,并确保它只计算is_healthy=True的记录。然后我们计算记录的数量。

如果你想按"分组对于特定字段,如patient_id,您可以使用:

DeviceHealthHistory.objects.filter(**filter_data).values('patient_id').annotate(
n=Count('pk', filter=Q(is_healthy=True))
).order_by('patient_id')

这将生成一个字典的查询集,其中'patient_id''n'作为键,患者和相应的计数作为值。

最新更新