How to fix AttributeError: 'WhereNode' object has no attribute 'select_format', raised by Django annotate()?
How to fix AttributeError: 'WhereNode' object has no attribute 'select_format', raised by Django annotate()?
SO 上有很多类似的问题,但我的任何搜索都没有出现这个特定的错误消息:
AttributeError: 'WhereNode' object has no attribute 'select_format'
这是在尝试 annotate()
具有比较(布尔)结果的 Django 查询集时引发的,例如以下简化示例中的 gt lookup:
Score.objects.annotate(positive=Q(value__gt=0))
模型看起来像这样:
class Score(models.Model):
value = models.FloatField()
...
如何解决这个问题?
可以使用 ExpressionWrapper()
修复这种情况
Score.objects.annotate(
positive=ExpressionWrapper(Q(value__gt=0), output_field=BooleanField()))
来自文档:
ExpressionWrapper
is necessary when using arithmetic on F()
expressions with different types ...
Q
对象显然也是如此,尽管我在 docs.
中找不到任何明确的引用
SO 上有很多类似的问题,但我的任何搜索都没有出现这个特定的错误消息:
AttributeError: 'WhereNode' object has no attribute 'select_format'
这是在尝试 annotate()
具有比较(布尔)结果的 Django 查询集时引发的,例如以下简化示例中的 gt lookup:
Score.objects.annotate(positive=Q(value__gt=0))
模型看起来像这样:
class Score(models.Model):
value = models.FloatField()
...
如何解决这个问题?
可以使用 ExpressionWrapper()
修复这种情况Score.objects.annotate(
positive=ExpressionWrapper(Q(value__gt=0), output_field=BooleanField()))
来自文档:
ExpressionWrapper
is necessary when using arithmetic onF()
expressions with different types ...
Q
对象显然也是如此,尽管我在 docs.