Created
March 10, 2011 12:37
-
-
Save ostronom/864033 to your computer and use it in GitHub Desktop.
Django ComputedField
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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