Saturday, March 29, 2014

Annotate concat() of two fields

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

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CA%2BDCN_v5zus5GXQ_KvdPthr5bRCS5xNwL4SVsK8eF8CiE2XUkg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment