Last active
January 16, 2017 15:48
-
-
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
This file contains 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
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