How to add two Field Instances in a Django Model into a variable?

Viewed 170

Good day! I'm trying to understand if there is a proper way of adding name_first & name_last Fields in the Customer Model into name_full Field. The name_full Field will be used as ftring renurn value for the Model. Relation with the Order Model via Foreign Key.

class Customer(models.Model):
    name_first = models.CharField(max_length=30, null=False, blank=False)
    name_last = models.CharField(max_length=30, null=False, blank=False)
    # name_full = ... name_first+name_last

def __str__(self):
    return self.name_full 

I've tried looking for similar question and there is a slight chance of not knowing how to ask a proper question) Cheers!

2 Answers

You can .annotate(…) [Django-doc] and use Concat [Django-doc] to concatenate the values:

from django.db.models import CharField, Value
from django.db.models.functions import Concat

Customer.objects.annotate(
    full_name=Concat(
        'name_first', Value(' '), 'name_last',
        output_field=CharField()
    )
).filter(
    full_name='Serhii Didukh'
)

If you want name_full field to be just another model field, you can add it as such, and override save() method in order to set it to the concat of name_first and name_last everytime the instance is saved:

class Customer(models.Model):
    name_first = models.CharField(max_length=30, null=False, blank=False)
    name_last = models.CharField(max_length=30, null=False, blank=False)
    name_full = models.CharField(max_length=30, null=False, blank=False)

def __str__(self):
    return self.name_full

def save(self)
    self.name_full = "{} {}".format(self.name_first, self.name_last)

    super().save()
Related