Created
May 27, 2012 16:40
-
-
Save arruda/2815002 to your computer and use it in GitHub Desktop.
Django - Models e métodos dinâmicos usando "templates"
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
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 |
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
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) |
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
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