Search code examples
pythondjangoconcatenationdjango-querysetdjango-annotate

How to concatenate two model fields in a Django QuerySet?


Consider a table called DataTable. It has two fields: A and B.

I want to return all rows from this table, and annotating a field called C which is a concatenation of A and B fields.

Here is what I have tried:

from django.db.models import CharField, Value
from .models import DataTable

def Test(request):
    query = DataTable.objects.all().annotate(C=Value('A' + '-' + 'B', 
          output_field=CharField()))
    # the rest of the function...

The problem here is that C is literally just the string literal "A - B" for every returned row.

I want to concatenate the values of A and B fields.


Solution

  • looks like you need concat:

    from django.db.models import CharField, Value
    from django.db.models.functions import Concat
    
    query = DataTable.objects.annotate(C=Concat('A', 
              Value('-'), 'B', output_field=CharField()))