Skip to content

Commit

Permalink
Restore cast-on-assign behavior on Django 1.8+
Browse files Browse the repository at this point in the history
Turns out the future-deprecated SubfieldBase class did more
than what was initially thought.  Since it is removed in
Django 1.10+, for clarity we no longer use it at all.
Instead we intern the behavior of its `Creator` descriptor
class as `CastOnAssignDescriptor`.

Fixes #60
Refs https://code.djangoproject.com/ticket/26807
Refs 8260050
  • Loading branch information
akx committed Jun 27, 2016
1 parent ba23793 commit 4c9678c
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 10 deletions.
26 changes: 24 additions & 2 deletions enumfields/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,28 @@
from .compat import import_string
from .forms import EnumChoiceField

metaclass = models.SubfieldBase if django.VERSION < (1, 8) else type

class CastOnAssignDescriptor(object):
"""
A property descriptor which ensures that `field.to_python()` is called on _every_ assignment to the field.
class EnumFieldMixin(six.with_metaclass(metaclass)):
This used to be provided by the `django.db.models.subclassing.Creator` class, which in turn
was used by the deprecated-in-Django-1.10 `SubfieldBase` class, hence the reimplementation here.
"""

def __init__(self, field):
self.field = field

def __get__(self, obj, type=None):
if obj is None:
return self
return obj.__dict__[self.field.name]

def __set__(self, obj, value):
obj.__dict__[self.field.name] = self.field.to_python(value)


class EnumFieldMixin(object):
def __init__(self, enum, **options):
if isinstance(enum, six.string_types):
self.enum = import_string(enum)
Expand All @@ -25,6 +43,10 @@ def __init__(self, enum, **options):

super(EnumFieldMixin, self).__init__(**options)

def contribute_to_class(self, cls, name):
super(EnumFieldMixin, self).contribute_to_class(cls, name)
setattr(cls, name, CastOnAssignDescriptor(self))

def to_python(self, value):
if value is None or value == '':
return None
Expand Down
8 changes: 0 additions & 8 deletions tests/test_django_admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@
import pytest
from django.core.urlresolvers import reverse

from enumfields import EnumIntegerField

from .enums import Color, IntegerEnum, Taste, ZeroEnum
from .models import MyModel

Expand Down Expand Up @@ -71,9 +69,3 @@ def test_model_admin_filter(admin_client, q_color, q_taste, q_int_enum):
count = int(re.search('(\d+) my model', response.content.decode('utf8')).group(1))
# and compare it to what we expect.
assert count == MyModel.objects.filter(**lookup).count()


def test_django_admin_lookup_value_for_integer_enum_field():
field = EnumIntegerField(Taste)

assert field.get_prep_value(str(Taste.BITTER)) == 3, "get_prep_value should be able to convert from strings"
34 changes: 34 additions & 0 deletions tests/test_issue_60.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import pytest

from .models import MyModel

try:
from .enums import Color # Use the new location of Color enum
except ImportError:
Color = MyModel.Color # Attempt the 0.7.4 location of color enum


@pytest.mark.django_db
def test_fields_value_is_enum_when_unsaved():
obj = MyModel(color='r')
assert Color.RED == obj.color


@pytest.mark.django_db
def test_fields_value_is_enum_when_saved():
obj = MyModel(color='r')
obj.save()
assert Color.RED == obj.color


@pytest.mark.django_db
def test_fields_value_is_enum_when_created():
obj = MyModel.objects.create(color='r')
assert Color.RED == obj.color


@pytest.mark.django_db
def test_fields_value_is_enum_when_retrieved():
MyModel.objects.create(color='r')
obj = MyModel.objects.first()
assert Color.RED == obj.color

0 comments on commit 4c9678c

Please sign in to comment.