SHARE
TWEET

Untitled

a guest Aug 25th, 2019 72 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. from enum import Enum
  2.  
  3.  
  4. class EnumModelChoices(Enum):
  5.     """
  6.     Helper for django model field choices.
  7.  
  8.     Usage:
  9.  
  10.         class Status(str, EnumModelChoices):
  11.             ACTIVE = 'active'
  12.             EXPIRED = 'expired'
  13.             SPENT = 'spent'
  14.  
  15.             @classmethod
  16.             def get_labels_map(cls):
  17.                 return {
  18.                     cls.ACTIVE: 'активен',
  19.                     cls.EXPIRED: 'истек',
  20.                     cls.SPENT: 'исчерпан',
  21.                 }
  22.  
  23.  
  24.         class Order(db.Model):
  25.             status = models.CharField(
  26.                 max_length=Status.max_length(),
  27.                 choices=Status.choices(),
  28.                 default=Status.ACTIVE,
  29.             )
  30.     """
  31.  
  32.     @classmethod
  33.     def labels_map(cls):
  34.         """
  35.         Maps values to readable values.
  36.  
  37.         Format: {constant value: readable value}
  38.  
  39.         """
  40.  
  41.         return {}
  42.  
  43.     @classmethod
  44.     def choices(cls):
  45.         """
  46.         Makes the model choices as follows:
  47.  
  48.             (
  49.                 ('PAID', 'readable value'),
  50.                 ('CANCELED', 'readable value'),
  51.                 ('WAITING', 'readable value'),
  52.             )
  53.         """
  54.  
  55.         return tuple(((k.value, v) for k, v in cls.get_labels_map().items()))
  56.  
  57.     @classmethod
  58.     def max_length(cls):
  59.         """
  60.         Finds the longest value and returns its length.
  61.         """
  62.  
  63.         return len(max([x.value for x in cls], key=len))
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top