How to create new field in output by annotate() with default value?

Viewed 2166

In SQL it would be:

SELECT *, 0 as new_field FROM table;

I thought in Django it would be like

Article.objects.annotate(new_field=0)

but it doesn't work; I get the error:

TypeError: QuerySet.annotate() received non-expression(s): 0.

Is there the way to do it?

3 Answers

another solution you can try value-expressions:

from django.db.models import Value, IntegerField

Article.objects.annotate(new_field=Value(0, output_field=IntegerField()))

What you can do is make use of Coalesce.

from django.db.models.functions import Coalesce

Article.objects.annotate(annotated=Coalesce(Count("field"), 0))

If you want the exact same behaviour of this SQL statement: SELECT 0 as new_field ...

You can use:

Article.objects.extra({'new_field': 0})
Related