porton
porton

Reputation: 5805

Django: annotate() does not work

Let Post be a model. I need to write a query which has a "constant" field type whose value is the string "X" for every object.

I try to do the following:

>>> Post.objects.all().annotate(type="X")
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/porton/.virtualenv/opus/lib/python3.6/site-packages/django/db/models/query.py", line 929, in annotate
    clone.query.add_annotation(annotation, alias, is_summary=False)
  File "/home/porton/.virtualenv/opus/lib/python3.6/site-packages/django/db/models/sql/query.py", line 982, in add_annotation
    annotation = annotation.resolve_expression(self, allow_joins=True, reuse=None,
AttributeError: 'str' object has no attribute 'resolve_expression'

Why the error and how to solve my problem?

Note that I need this for distinguishing different kinds of results when I .union() several queries together:

    q1 = paybills.models.PaymentSuccess.objects.all().annotate(type='PaymentSuccess').values('created', 'type')
    q2 = paybills.models.SubscriptionSuccess.objects.all().annotate(type='SubscriptionSuccess').values('created', 'type')
    q3 = paybills.models.SubscriptionPayment.objects.all().annotate(type='SubscriptionPayment').values('created', 'type')
    q4 = paybills.models.UnsubscriptionSuccess.objects.all().annotate(type='UnsubscriptionSuccess').values('created', 'type')
    q = q1.union(q2, q3, q4, all=True).order_by('-created')

Upvotes: 1

Views: 1444

Answers (2)

MarcinEl
MarcinEl

Reputation: 219

In this situation You don't need to use all()

from django.db.models import Value
q1 = paybills.models.PaymentSuccess.objects.annotate(type=Value('PaymentSuccess')).values('created', 'type')

Upvotes: 1

albar
albar

Reputation: 3100

Try to use Value:

from django.db.models import Value
Post.objects.all().annotate(type=Value("X"))

Upvotes: 6

Related Questions