Created
March 28, 2012 18:10
-
-
Save ricardodani/2228902 to your computer and use it in GitHub Desktop.
Metaprog em model.Field com conteúdo Json (Django)
This file contains 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
from django.db import models | |
from django.utils import simplejson | |
_NULL = {'blank': True, 'null': True} | |
class Modelo(models.Model): | |
u''' | |
Modelo com metaprogramação baseada no field json_content (oriundo de um webservice) | |
''' | |
titulo = models.CharField('título', max_length=255) | |
# Conteúdo do json cacheado na base | |
json_content = models.TextField(**_NULL) | |
# Content loaded ? | |
_ctload = False | |
def __unicode__(self): | |
return self.titulo | |
def _load_json_content(self): | |
self._content = simplejson.loads(self.json_content, 'utf-8') | |
self._ctload = True | |
def __getattr__(self, attr): | |
try: | |
return super(Modelo, self).__getattr__(attr) | |
except AttributeError: | |
if not self._ctload: | |
self._load_json_content() | |
try: | |
return self._content[attr] | |
except KeyError: | |
raise AttributeError |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment