Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating into a new field in a Django query

Tags:

python

django

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

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...

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.

like image 446
bvmcode Avatar asked Mar 07 '23 02:03

bvmcode


2 Answers

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()))
like image 61
Brown Bear Avatar answered Mar 08 '23 17:03

Brown Bear


Basically there are two approaches to achieve it.

First one:
First of all, you need to import the following expressions.

from django.db.models import F, Value, Func

then, concatenate the fields as below:

ann_concat = Customer.objects.annotate(
            fullName = Func(F('first_name'), Value(' '),F('last_name'), function= 'CONCAT'))

In above example, I have concatenated first name and last name into a new field called fullName.

Second one: This approach is way shorter than the first one you only need to import Concat() and Value() for making the spaces functions.

from django.db.models.functions import Concat


  short_syntax = Customer.objects.annotate(full_name = Concat('first_name',Value(' '),'last_name'))
like image 44
Abdu4 Avatar answered Mar 08 '23 18:03

Abdu4