Django:annotate()不起作用

波顿

让我们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'

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

请注意,当我.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')
阿尔巴

尝试使用Value

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章