Utsav T
Utsav T

Reputation: 1545

Django - Saving a model using Admin

I have created a simple model - the instances of which I will be saving through the admin interface.

The field hashval needs to have the hashed value of title. It seems to just have the default hashvalue for every entry. How do I fix that ? Additionally, it should also get updated when title is updated. Any help in achieving this will be much appreciated. (Please point out if any duplicates exist)

class Entry(models.Model):
created = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=50)
content = models.TextField()
hashval = models.BigIntegerField()
hashval = abs(hash(title))

def __unicode__(self):
    return smart_unicode(self.title + " " + str(self.hashval))

class Meta:
    verbose_name_plural = 'Entries'

Upvotes: 0

Views: 42

Answers (1)

schillingt
schillingt

Reputation: 13731

One option is to override your save method to apply this before it's saved.

class Entry(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=50)
    content = models.TextField()
    # Need to specify it as blank=True here or 
    # in the form so it can be ignored when the form is cleaned
    hashval = models.BigIntegerField(blank=True)

    def save(self, *args, **kwargs):
        self.hashval = abs(hash(self.title))
        return super(Entry, self).save(*args, **kwargs)

Upvotes: 1

Related Questions