How to fix AttributeError: 'WhereNode' object has no attribute 'select_format', raised by Django annotate()?

Viewed 645

There are many similar questions on SO, but this specific error message did not turn up in any of my searches:

AttributeError: 'WhereNode' object has no attribute 'select_format'

This was raised when trying to annotate() a Django queryset with the (boolean) result of a comparison, such as the gt lookup in the following simplified example:

Score.objects.annotate(positive=Q(value__gt=0))

The model looks like this:

class Score(models.Model):
    value = models.FloatField()
    ...

How to fix this?

1 Answers

This case can be fixed using the ExpressionWrapper()

Score.objects.annotate(
    positive=ExpressionWrapper(Q(value__gt=0), output_field=BooleanField()))

From the docs:

ExpressionWrapper is necessary when using arithmetic on F() expressions with different types ...

The same apparently holds for Q objects, although I could not find any explicit reference in the docs.

Related