MCPcopy Index your code
hub / github.com/MongoEngine/mongoengine / EnumField

Class EnumField

mongoengine/fields.py:1590–1666  ·  view source on GitHub ↗

Enumeration Field. Values are stored underneath as is, so it will only work with simple types (str, int, etc) that are bson encodable Example usage: .. code-block:: python class Status(Enum): NEW = 'new' ONGOING = 'ongoing' DONE = 'done'

Source from the content-addressed store, hash-verified

1588
1589
1590class EnumField(BaseField):
1591 """Enumeration Field. Values are stored underneath as is,
1592 so it will only work with simple types (str, int, etc) that
1593 are bson encodable
1594
1595 Example usage:
1596
1597 .. code-block:: python
1598
1599 class Status(Enum):
1600 NEW = 'new'
1601 ONGOING = 'ongoing'
1602 DONE = 'done'
1603
1604 class ModelWithEnum(Document):
1605 status = EnumField(Status, default=Status.NEW)
1606
1607 ModelWithEnum(status='done')
1608 ModelWithEnum(status=Status.DONE)
1609
1610 Enum fields can be searched using enum or its value:
1611
1612 .. code-block:: python
1613
1614 ModelWithEnum.objects(status='new').count()
1615 ModelWithEnum.objects(status=Status.NEW).count()
1616
1617 The values can be restricted to a subset of the enum by using the ``choices`` parameter:
1618
1619 .. code-block:: python
1620
1621 class ModelWithEnum(Document):
1622 status = EnumField(Status, choices=[Status.NEW, Status.DONE])
1623 """
1624
1625 def __init__(self, enum, **kwargs):
1626 self._enum_cls = enum
1627 if kwargs.get("choices"):
1628 invalid_choices = []
1629 for choice in kwargs["choices"]:
1630 if not isinstance(choice, enum):
1631 invalid_choices.append(choice)
1632 if invalid_choices:
1633 raise ValueError("Invalid choices: %r" % invalid_choices)
1634 else:
1635 kwargs["choices"] = list(self._enum_cls) # Implicit validator
1636 super().__init__(**kwargs)
1637
1638 def validate(self, value):
1639 if isinstance(value, self._enum_cls):
1640 return super().validate(value)
1641 try:
1642 self._enum_cls(value)
1643 except ValueError:
1644 self.error(f"{value} is not a valid {self._enum_cls}")
1645
1646 def to_python(self, value):
1647 value = super().to_python(value)

Callers 7

ModelWithEnumClass · 0.90
ModelComplexEnumClass · 0.90
ModelWithDefaultClass · 0.90
test_partial_choicesMethod · 0.90
test_wrong_choicesMethod · 0.90
ModelWithColorClass · 0.90
ModelWithFunkyColorClass · 0.90

Calls

no outgoing calls

Tested by 2

test_partial_choicesMethod · 0.72
test_wrong_choicesMethod · 0.72