Skip to content

Instantly share code, notes, and snippets.

@igorsobreira
Created January 25, 2010 17:32
Show Gist options
  • Save igorsobreira/286051 to your computer and use it in GitHub Desktop.
Save igorsobreira/286051 to your computer and use it in GitHub Desktop.
wondering how dynamic fields could be added to a model...
# wondering how dynamic fields could be added to a model...
import copy
from django.db import models
class DynamicModel(models.base.ModelBase):
def _prepare(cls):
# calling a function or method to return the extra fields to
# add to the model
for field_name, field in get_extra_fields():
cls.add_to_class(field_name, copy.deepcopy(field))
models.base.ModelBase._prepare(cls)
#### this is what the user would have to create
## the function that returns the fields to add
def get_extra_fields():
test_fields = (
("author", models.ForeignKey("auth.User")),
)
return test_fields
class News(models.Model):
## find a way to customize the model metaclass, the problem if we
## adding extra fields, we don't want to change the model code, so
## we need a (hacky) way to add this metaclass...
__metaclass__ = DynamicModel
title = models.CharField(max_length=100)
content = models.TextField()
def __unicode__(self):
return self.title
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment