Stupid.Fat.Cat
Stupid.Fat.Cat

Reputation: 11295

Django, how do you set the value of a field in a model to be a hash of one of the fields?

This is what my model looks like:

class Alert(models.Model):
    hash = models.CharField(max_length=64, unique=True)
    raw_line = models.TextField()
    alert_datetime = models.DateTimeField()
    datetime_dismissed = models.DateTimeField(null=True)

and when I create an Alert, I set the hash value as something. But, I read that I can effectively do this:

hash = models.CharField(max_length=64, unique=True, default=some_hash_function)

def some_hash_function():
    ...
    return some_hash

But the hash I want relies on raw_line, is it possible to have the function hash the raw_line and set it by default?

Some additional context:

I've tried doing the following:

class Alert(models.Model):
    hash = models.CharField(max_length=64, unique=True, default=hash_raw_line)
    raw_line = models.TextField()
    alert_datetime = models.DateTimeField()
    datetime_dismissed = models.DateTimeField(null=True)

    def hash_raw_line(self):
        return hashlib.sha256(self.raw_line).hexdigest()

but it seems like the it can't find the reference for hash_raw_line

Upvotes: 2

Views: 2359

Answers (1)

Ammar Alyousfi
Ammar Alyousfi

Reputation: 4372

You can do so by overriding the save() method of Alert model:

class Alert(models.Model):
hash = models.CharField(max_length=64, unique=True, default=None)
raw_line = models.TextField()
alert_datetime = models.DateTimeField()
datetime_dismissed = models.DateTimeField(null=True)

def save(self, *args, **kwargs):
    if self.hash is None:
        self.hash = hashlib.sha256(self.raw_line).hexdigest()
    super().save(*args, **kwargs)  # Call the "real" save() method.

Notice that default = None is added to the hash field.

Upvotes: 3

Related Questions