Home > Mobile >  The annotation 'id' conflicts with a field on the model
The annotation 'id' conflicts with a field on the model

Time:12-27

In Annotate I am trying to get the count of quires for which is_healthy is True but I am getting an Error The annotation 'id' conflicts with a field on the model. Any solution to solve this? and why is this causing how can i resolve this?

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

CodePudding user response:

If you are just looking for count then you use count function fo queryset:

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

To get other fields along with the count.

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

CodePudding user response:

You should count with:

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

This will filter on the **filter_data and also ensure that it only counts records with is_healthy=True. We then count the number of records.

If you want to "group by" a certain field, like patient_id, you can work with:

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

This will produce a queryset of dictionaries with 'patient_id' and 'n' as keys, and the patient and the corresponding counts as values.

  • Related