Skip to content

Instantly share code, notes, and snippets.

@ostronom
Created March 10, 2011 12:37
Show Gist options
  • Save ostronom/864033 to your computer and use it in GitHub Desktop.
Save ostronom/864033 to your computer and use it in GitHub Desktop.
Django ComputedField
class ComputedField(TextField):
def __init__(self, *args, **kwargs):
kwargs['editable'] = False
kwargs['blank'] = True
if 'computation' not in kwargs:
raise AttributeError("ComputedField *REQUIRES* computation parameter")
self.computation = kwargs.pop('computation')
if not callable(self.computation):
raise AttributeError("ComputedField computation parameter *MUST* be callable")
super(ComputedField, self).__init__(*args, **kwargs)
def pre_save(self, model_instance, add):
value = ''
if not add:
value = self.computation(model_instance)
setattr(model_instance, self.attname, value)
return value
class Entry(models.Model):
title = models.CharField(max_length = 200, verbose_name = u'Заголовок')
pubdate = models.DateField(verbose_name = u'Дата публикации', auto_now = True)
text = models.TextField(verbose_name = u'Текст')
shortlink = ComputedField(computation = lambda w: googgl.shorten_url('<domainname>' + w.get_absolute_url()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment