GTA.sprx
GTA.sprx

Reputation: 827

Combine 2 CharFields to form an attribute

I want combine the first_name and last_name fields to create a full_name field. Which will then be used to create the slug.

I get NameError: name 'self' is not defined with this code.

class Employee(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50, null=True, blank=True)
    full_name = self.first_name + " " + self.last_name 
    slug = AutoSlugField(null=True, default=None, unique=True, populate_from='full_name')

Upvotes: 0

Views: 368

Answers (2)

sandeshdaundkar
sandeshdaundkar

Reputation: 903

you can create a property in the class. This returns slug property as

>>> e.slug
'sandesh-daundkar'
class Employee(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50, null=True, blank=True)
    slug = AutoSlugField(null=True, default=None, unique=True, populate_from='full_name')

    @property
    def full_name(self):
        return f"{self.first_name} {self.last_name}"

Upvotes: 1

Amar
Amar

Reputation: 666

Class methods can be soultion

class Employee(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50, null=True, blank=True)
    slug = AutoSlugField(null=True, default=None, unique=True, populate_from='full_name')

    @property
    def last_name(self):
        full_name = self.first_name + " " + self.last_name
        return full_name

Upvotes: 0

Related Questions