.@company.com". So, I wrote" /> .@company.com". So, I wrote" /> .@company.com". So, I wrote"/>

Overriding create() method in the model manager doesn't do anything

581 Views Asked by At

I have a model employee, and while creating an instance I want to automatically set their email to "<first_name>.<last_name>@company.com". So, I wrote a manager to do the pre-processing:

class EmployeeManager(models.Manager):
    def create(self, **kwargs):
        name = kwargs['first_name']
        surname = kwargs['last_name']
        kwargs['email'] = f'{name}.{surname}@company.com'
        return super(EmployeeManager, self).create(**kwargs)

class Employee(models.Model):
    first_name = models.CharField(null=False, blank=False, default="employee", max_length=255)
    last_name = models.CharField(null=False, blank=False, default="employee", max_length=255)
    position = models.CharField(null=False, blank=False, default="SDE", max_length=255)
    email = models.EmailField(null=False, default="[email protected]", unique=True)
    phone = models.CharField(null=False, blank=False, default='1234567890', max_length=10, validators=[MinLengthValidator])
    slack_id = models.UUIDField(null=False, blank=True, default = uuid.uuid4)
    active = models.BooleanField(default=True)

    objects = EmployeeManager()

    def __str__(self) -> str:
        return self.email

However, when I am creating an instance of this model using the admin interphase, the email is set to the default value ([email protected]) and not what I am feeding it in the new create() method. Why is this happening?

1

There are 1 best solutions below

0
Hashem On

I suggest to use Save method on your model

def save(self, *args, **kwargs):
     self.email = f'{self.first_name}.{self.last_name}@company.com'
     super(Employee, self).save(*args, **kwargs)