Skip to content

Commit

Permalink
Add contrib methods to make setting work correctly
Browse files Browse the repository at this point in the history
  • Loading branch information
Adam DePue committed Aug 3, 2016
1 parent 4b8a7fe commit 5bf630b
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions src/django_richenum/models/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,35 @@
from richenum import RichEnumValue, OrderedRichEnumValue


# https://github.com/django/django/blob/64200c14e0072ba0ffef86da46b2ea82fd1e019a/django/db/models/fields/subclassing.py#L31-L44
class Creator(object):
"""
A placeholder class that provides a way to set the attribute on the model.
"""
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 IndexEnumField(models.IntegerField):
'''Store ints in DB, but expose OrderedRichEnumValues in Python.
'''
description = 'Efficient storage for OrderedRichEnums'

def contribute_to_class(self, cls, name, **kwargs):
super(IndexEnumField, self).contribute_to_class(cls, name, **kwargs)

# Add Creator descriptor to allow the field to be set directly
setattr(cls, self.name, Creator(self))

def __init__(self, enum, *args, **kwargs):
if not hasattr(enum, 'from_index'):
raise TypeError("%s doesn't support index-based lookup." % enum)
Expand Down Expand Up @@ -110,6 +133,12 @@ class CanonicalNameEnumField(models.CharField):
'''
description = 'Storage for RichEnums'

def contribute_to_class(self, cls, name, **kwargs):
super(CanonicalNameEnumField, self).contribute_to_class(cls, name, **kwargs)

# Add Creator descriptor to allow the field to be set directly
setattr(cls, self.name, Creator(self))

def __init__(self, enum, *args, **kwargs):
if not hasattr(enum, 'from_canonical'):
raise TypeError("%s doesn't support canonical_name lookup." % enum)
Expand Down

0 comments on commit 5bf630b

Please sign in to comment.