Skip to content

Instantly share code, notes, and snippets.

@arruda
Created May 27, 2012 16:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arruda/2815002 to your computer and use it in GitHub Desktop.
Save arruda/2815002 to your computer and use it in GitHub Desktop.
Django - Models e métodos dinâmicos usando "templates"
def model_factory(name,desc,field):
"""Fabricates a model with the given name, using MODEL_TEMPLATE as reference.
"""
format_dict = {
'CLASS_NAME' : name.capitalize(),
'CLASS_DESC' : desc,
'FIELD_NAME' : field,
}
model_source = MODEL_TEMPLATE % format_dict
return model_source
MY_MODELS_LIST = (
{'name':'Foo','desc':'Foo model', 'field':'foo_field'},
{'name':'Bars','desc':'Bars model', 'field':'bars_field'},
{'name':'Other','desc':'Other model', 'field':'other_field'},
)
#runs the generated models sources
for model_infos in MY_MODELS_LIST:
model_source = model_factory(model_infos['name'],model_infos['desc'],model_infos['field'])
exec(model_source)
MODEL_TEMPLATE =\
"""
class %(CLASS_NAME)s(models.Model):
"%(CLASS_DESC)s"
%(FIELD_NAME)s = models.CharField(max_length=256)
def __unicode__(self):
return self.%(FIELD_NAME)s
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment