Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add implementation of IntFlag as ListField of IntEnumField #22

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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