Skip to content

Instantly share code, notes, and snippets.

@otov4its
Last active January 16, 2017 15:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save otov4its/4543540f3f893122ece654d81fee80bc to your computer and use it in GitHub Desktop.
Save otov4its/4543540f3f893122ece654d81fee80bc to your computer and use it in GitHub Desktop.
Django NullCharField subclass of the CharField that allows empty strings to be stored as NULL in database
from django.db.models import CharField
from django.core.exceptions import ImproperlyConfigured
from django.utils.translation import ugettext_lazy as _
class NullCharField(CharField):
"""
Subclass of the CharField that allows
empty strings to be stored as NULL in database
"""
description = _("CharField that stores '' as None and returns None as ''")
def __init__(self, *args, **kwargs):
if not kwargs.get('null', True) or not kwargs.get('blank', True):
raise ImproperlyConfigured(
'NullCharField implies null==blank==True')
kwargs['null'] = kwargs['blank'] = True
super().__init__(*args, **kwargs)
def to_python(self, value):
val = super().to_python(value)
return '' if val is None else val
def get_prep_value(self, value):
prep_value = super().get_prep_value(value)
return None if prep_value == '' else prep_value
def deconstruct(self):
"""
For migration purposes
"""
name, path, args, kwargs = super().deconstruct()
del kwargs['null']
del kwargs['blank']
return name, path, args, kwargs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment