Home > Software engineering >  How to equate the field of a model with another field in the same model?
How to equate the field of a model with another field in the same model?

Time:10-08

I would like the external_id field to always inherit the temporary_id values (for experimental purposes).

I just want it to be equal to the temporary_id field. How do I do this?

# External parts Lookup table
class External(models.Model):
    temporary_id = models.CharField(max_length=32, unique=True)                                      # Unique temporary external id
    actual_id = models.CharField(max_length=32, unique=True, blank=True)                             # Unique actual external id
    external_id = temporary_id                                                
    # Display below in admin 
    def __str__(self): 
       return f"{self.external_id}"

CodePudding user response:

you can override the save method

class External(models.Model):
      temporary_id = models.CharField(max_length=32, unique=True)                                      
      actual_id = models.CharField(max_length=32, unique=True, blank=True)                             
      external_id = models.CharField(max_length=32,blank=True, null=True)
                                           
      def __str__(self): 
         return f"{self.external_id}"

      def save(self, *args, **kwargs):
         self.external_id = self.temporary_id
         super(External, self).save(*args, **kwargs)
  • Related