I have a queryset in my Django views.py
. I’m using annotate
to add a promo
property to each object based on each object’s id
. However this is not working:
JavaScript
9
1
bytes = Byte.objects.filter(
2
published=True
3
).annotate(
4
# add path to promo image based on byte's id property
5
promo=Value('../static/images/promo-'+id+'.png', output_field=CharField())
6
).order_by(
7
'-publish_date'
8
)
9
I get the error: name 'id' is not defined
Advertisement
Answer
The way you try you are trying to access a variable id. Try using the Concat function:
JavaScript
11
1
from django.db.models.functions import Concat
2
3
bytes = Byte.objects.filter(
4
published=True
5
).annotate(
6
# add path to promo image based on byte's id property
7
promo=Concat(Value('../static/images/promo-'), 'id', Value('.png'), output_field=CharField())
8
).order_by(
9
'-publish_date'
10
)
11
Reference: Django database Functions – Concat.