Enum Field

This section will cover how do you create Enumeration Data field on Model & DTO.


How to create enum field on Model & DTO?

  • I am assume that you are following our directory structure of Back-end.

  • Let’s call the module name marketing and notification is a feature of that module

  • We have to add the enum filed type called type into the notification feature & values will be

    • SMS

    • Push

    • Email


Step by Step Create Enum file

  • Create file Structure :module_name_enum.py Name marketing_enum.py. Here our notification system add under marketing module. If the file already exist then just add the list to the existing file. Under marketing/marketing/data/marketing_enum.py

  • Added the type and value list like below

  • Key should be all Camelcase

from pfms.common.enum_processor import BaseEnum


class NotificationType(BaseEnum):
    SMS = "SMS"
    Push = "Push"
    Email = "Email"


Step by Step Add Enum into Model.

  • Assume that you already have a model called notification.py

  • Field name is type

from marketing.data.marketing_enum import NotificationType
from pf_sqlalchemy.db.orm import Base, database


class Notification(Base):
    ...

    type = database.Column("type", database.Enum(NotificationType), default=NotificationType.PUSH, nullable=False)

    ...


Step by Step Add Enum into DTO.

  • Assume that you already have a model called notification_dto.py

  • Field name is type

from marketing.data.marketing_enum import NotificationType
from marketing.model.notification import Notification
from marshmallow import fields
from pfms.common.enum_processor import EnumField
from pfms.pfapi.base.pfms_base_schema import PfDetailBaseSchema


class NotificationDetailsDto(PfDetailBaseSchema):

    class Meta:
        model = Notification
        load_instance = True

    ...

    type = EnumField(NotificationType, required=True, error_messages={"required": "Please Enter Type"})

    ...