Skip to content
Advertisement

Django: Make a Queryset with annotate using an object’s property

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:

    bytes = Byte.objects.filter(
        published=True
    ).annotate(
        # add path to promo image based on byte's id property
        promo=Value('../static/images/promo-'+id+'.png', output_field=CharField())
    ).order_by(
        '-publish_date'
    )

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:

from django.db.models.functions import Concat

bytes = Byte.objects.filter(
    published=True
).annotate(
    # add path to promo image based on byte's id property
    promo=Concat(Value('../static/images/promo-'), 'id', Value('.png'), output_field=CharField())
).order_by(
    '-publish_date'
)

Reference: Django database Functions – Concat.

Advertisement