Django:注释()不起作用

por*_*ton 1 django django-models

Post是一个模型。我需要编写一个查询,它有一个“常量”字段,type其值是"X"每个对象的字符串。

我尝试执行以下操作:

>>> 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'
Run Code Online (Sandbox Code Playgroud)

为什么会出现错误以及如何解决我的问题?

请注意,当我将.union()多个查询放在一起时,我需要它来区分不同类型的结果:

    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')
Run Code Online (Sandbox Code Playgroud)

alb*_*bar 5

尝试使用Value

from django.db.models import Value
Post.objects.all().annotate(type=Value("X"))
Run Code Online (Sandbox Code Playgroud)