Skip to content

Instantly share code, notes, and snippets.

@phill-tornroth
Created April 4, 2012 18:46
Show Gist options
  • Save phill-tornroth/2304655 to your computer and use it in GitHub Desktop.
Save phill-tornroth/2304655 to your computer and use it in GitHub Desktop.
Playing with DictShield model creation from Django
from dictshield.document import Document
from dictshield.fields import StringField, IntField
from django.db import models
def _build_client_model(model):
"""
Take a Django model, and return a DictShield Document subclass
which is very representative.
TODO:
- null/blank support
- bounds for numbers (min/max/positive, etc.)
- lots more field types
"""
class_name = 'Client%s' % (model.__class__.__name__,)
fields = {}
for field in model._meta.fields:
if isinstance(field, models.CharField) \
or isinstance(field, models.TextField):
fields[field.name] = StringField(max_length=field.max_length)
elif isinstance(field, models.IntegerField):
# Includes all variations of Integers, including 'Big', 'Small',
# and 'Positive' Variations
fields[field.name] = IntField()
else:
print "We don't support %s fields just yet" % (field.__class__.__name__)
new_class = type(class_name, (Document,), fields)
return new_class
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment