Is there a way to customize the value of specific field in a model in django when adding a new data?

Question:

I have a model here which I want to specify the value of unique_code everytime I’m adding a new data .

model.py

class Customer(models.Model):
    LastName = models.CharField(max_length=45, blank=True)
    FirstName = models.CharField(max_length=45, blank=True)
    MiddleName = models.CharField(max_length=45, blank=True)
    ExtensionName = models.CharField(max_length=45, blank=True)
    GenderID = models.ForeignKey(Gender, on_delete=models.CASCADE)
    id_pic = models.ImageField(null=True, blank=True, upload_to=upload_path)
    otp = models.CharField(max_length=6, blank=True)
    unique_code = models.CharField(max_length=8, blank=True)
    verified = models.BooleanField(default=False)
    already_claimed = models.BooleanField(default=False)
    email = models.CharField(max_length=45, blank=True)
    Birthdate = models.CharField(max_length=45, blank=True, null=True)
    cellphone_number = models.CharField(max_length=45, blank=True, null=True)
    agreement1 = models.BooleanField(null=True)
    agreement2 = models.BooleanField(null=True)
    agreement3 = models.BooleanField(null=True)

I try to override the save method to do that and here is my code

 def save(self, *args, **kwargs):
        self.unique_code = uuid.uuid4().hex[:8].upper()
        super().save(*args, **kwargs)

but the problem with this approach is that the unique_code change everytime I update the data. and I want the unique_code to not change once the data has been save to database.

so is it possible to specify its value here in view.py

  data = request.data
            serializer = CustomerSerializer(data=data)

how to add unique_code = uuid.uuid4().hex[:8].upper() in this serializer = CustomerSerializer(data=data)

Asked By: Mel Carlo Iguis

||

Answers:

You can simply test to see if it exists already in your save() function, and only call it if it’s not there. Then it will behave consistently across all attempts to save it.

def save(self, *args, **kwargs):
    if not self.unique_code:
         #object has no unique_code
         self.unique_code = uuid.uuid4().hex[:8].upper()
    super().save(*args, **kwargs)

Another approach is to always assign it on the first save, before the object has been assigned an ID. That way you know that any object that has been saved to the database will also have a unique_code

def save(self, *args, **kwargs):
    if not self.id:
         #object has no id
         self.unique_code = uuid.uuid4().hex[:8].upper()
    super().save(*args, **kwargs)
Answered By: SamSparx