让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')
答案 0 :(得分:4)
尝试使用Value
:
from django.db.models import Value
Post.objects.all().annotate(type=Value("X"))
答案 1 :(得分:1)
在这种情况下,您无需使用from django.db.models import Value
q1 = paybills.models.PaymentSuccess.objects.annotate(type=Value('PaymentSuccess')).values('created', 'type')
var img = new Image();
img.onload = function () {
alert("image is loaded");
}
img.src = "img.jpg";