LoginSignup
0
0

More than 5 years have passed since last update.

django-enumfieldを拡張してvalueとlabelのタプルのリストを返すメソッドを実装

Posted at

環境

  • Django 2.1.7
  • Python 3.6
  • django-enumfield 1.5

背景

DjangoモデルのフィールドをEnumで扱えるように拡張してくれる便利なdjango-enumfieldですが、標準で実装されているchoices()だと、Enum定義のvalueとnameのタブルリストが返却されます。

定義例

from django_enumfield import enum as django_enum
class UserType(django_enum.Enum):
    ADMIN = 1
    USER = 2

    labels = {
        ADMIN : "管理者",
        USER : "ユーザ",
    }

出力例

In : UserType.choices()
Out: [(1, ADMIN), (2, USER)]

せっかくlabel名を指定しているので、valueとlabelで受け取れるように拡張しました。

実装

拡張(choices2を実装)

class BaseType(django_enum.Enum):

    @classmethod
    def choices2(cls, blank=False):
        choices = sorted([(key, cls.label(key)) for key, value in cls.values.items()], key=lambda x: x[0])
        if blank:
            choices.insert(0, ('', ''))
        return choices

拡張したクラスを継承させます。

class UserType(BaseType):

出力例

In : UserType.choices2()
Out: [(1, '管理者'), (2, 'ユーザ')]

In : UserType.choices2(blank=True)
Out: [('',''),(1, '管理者'), (2, 'ユーザ')]

選択リスト(select)の選択肢(option)に使えます。choices2(blank=True)

<select>
  {% for user_type in user_type_list %}
    <option value="{{user_type.0}}">{{user_type.1}}</option>
  {% endfor %}
</select>
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0