Skip to content

Commit

Permalink
add implementation of IntFlag as ListField of IntEnumField
Browse files Browse the repository at this point in the history
  • Loading branch information
terencehonles committed Aug 1, 2018
1 parent 5e63e05 commit 24a4810
Showing 1 changed file with 36 additions and 1 deletion.
37 changes: 36 additions & 1 deletion extras_mongoengine/fields.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
import operator

from datetime import timedelta
from mongoengine.base import BaseField
from mongoengine.fields import IntField, StringField, EmailField
from mongoengine.fields import EmailField, IntField, ListField, StringField

try:
from functools import reduce
except ImportError:
# reduce is a builtin in Python2
pass


class TimedeltaField(BaseField):
Expand Down Expand Up @@ -105,6 +113,33 @@ class IntEnumField(EnumField, IntField):
pass


class IntFlagField(ListField):
def __init__(self, enum, **kwargs):
super(IntFlagField, self).__init__(IntEnumField(enum), **kwargs)

def __get__(self, instance, owner):
if instance is None:
return self

return self.field.enum(reduce(
operator.or_, instance._data.get(self.name, []), 0))

def __set__(self, instance, value):
# copy mongoengine
if value is None:
if self.null:
value = None
elif self.default is not None:
value = self.default
if callable(value):
value = value()

if value is not None and not isinstance(value, list):
value = [i for i in self.field.enum if i and i & value == i]

super(IntFlagField, self).__set__(instance, value)


class StringEnumField(EnumField, StringField):
"""A variation on :class:`EnumField` for only string containing enumeration.
"""
Expand Down

0 comments on commit 24a4810

Please sign in to comment.