简体   繁体   中英

Django database entry created by concatenation of two fields

I have the following Django model

class Labels(models.Model):
    user = models.CharField(max_length=200)
    label = models.CharField(max_length=200)
    live = models.CharField(max_length=1)
    unique_key = models.CharField(max_length=200)
    def __str__(self):
        return '%s / %s' % (self.user, self.label)

I would like unique_key to be automatically populated with a concatenation of md5(user + label)

eg

user = 'James'

label = 'KDJ'

concat = user + label unique_key = print(hashlib.md5(concat.encode()).hexdigest())

Output

1935636b374a17f87636460e4307f736

You can override save method for this:

class Labels(models.Model):

    def save(self, *args, **kwargs):
        concat = self.user + self.label
        self.unique_key = hashlib.md5(concat.encode()).hexdigest()
        super().save(*args, **kwargs)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM