Skip to content

Instantly share code, notes, and snippets.

@AdamG
Created March 6, 2012 16:21
Show Gist options
  • Save AdamG/1987190 to your computer and use it in GitHub Desktop.
Save AdamG/1987190 to your computer and use it in GitHub Desktop.
from django.db import models
from django.db.models.fields import CharField
class ModelField(CharField):
__metaclass__ = models.SubfieldBase
def __init__(self, **kwargs):
kwargs['blank'] = True
kwargs['max_length'] = 255
super(ModelField, self).__init__(**kwargs)
def pre_save(self, obj, add):
value = getattr(obj, self.attname)
if value is None:
return value
else:
return self._obj_to_data(value)
def get_db_prep_value(self, value, connection, prepared=False):
if prepared:
return self._obj_to_data(value)
if value is None: return None
elif isinstance(value, basestring): return value
else: return self._obj_to_data(value)
def _obj_to_data(self, obj):
return "{0}.{1}|{2}".format(obj.__module_, type(obj).__name__, obj.pk)
def to_python(self, value):
from django.core.exceptions import ValidationError
if not isinstance(value, basestring):
return value
if value == '':
return None
try:
pth, pk = value.split("|", 2)
pth_parts = pth.split(".")
module_path, model = pth_parts[:-1], pth_parts[-1]
module = ".".join(module_path)
try:
klass = getattr(__import__(module, [], [], [model]), model)
except AttributeError:
return None
try:
return klass.objects.get(pk=pk)
except klass.DoesNotExist:
return None
except ImportError:
raise ValidationError('Could not import the model: %s' % value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment