Annotate concat() of two fields

205 views
Skip to first unread message

Marc Aymerich

unread,
Mar 29, 2014, 2:05:12 PM3/29/14
to django-users
Hi, I want to annotate the concatenation of two string fields, something like

Domain.objects.annotate(annotation=F('field1')+F('field2'))

however it is not possible to use F expressions on annotate().

I'm trying to accomplish the same thing using extra() however I don't
know how to do it right, :(

I have the following Domain model:

class Domain(models.Model):
name = models.CharField(max_length=256, unique=True)
top = models.ForeignKey('domains.Domain', null=True)

which top being a self referencing field,

I want an annotation with the concatenation of "obj.top.name + obj.name"

What I have so far is something like

Domain.objects.select_related('top').extra(select={
'structured_name': 'CONCAT(T2.name, domains_domain.name)'
})

Notice that I'm using T2 which is the JOIN table, But this doesn't
always work, because it depends on the total number of joins performed
by the queryset, (so the name changes to T4, etc)

What would be the right way of doing this concat() annotation?

thanks!!
--
Marc
Reply all
Reply to author
Forward
0 new messages