Consider a table called DataTable. It has two fields, A and B. I want to return all rows of this table plus annotate a field called C that is a concatenation of A and B.
Here is what I have tried
JavaScript
x
8
1
from django.db.models import CharField, Value
2
from .models import DataTable
3
4
def Test(request):
5
query = DataTable.objects.all().annotate(C=Value('A' + '-' + 'B',
6
output_field=CharField()))
7
# the rest of the function...
8
problem here is that C is literally just the string literal “A – B” for every returned row. I want to use the actual values of A and B into that concatenation.
Advertisement
Answer
looks like you need concat:
JavaScript
1
6
1
from django.db.models import CharField, Value
2
from django.db.models.functions import Concat
3
4
query = DataTable.objects.annotate(C=Concat('A',
5
Value('-'), 'B', output_field=CharField()))
6