用于使用命名常量枚举的自定义django字段
django-enumfield-named-choices的Python项目详细描述
这个包基于django enumfield。 它被扩展以使django表单过滤器满意 在验证命名属性的输入时 而不是1,2,…
安装
在python环境中安装django-enumfield-named-choices:
$ pip install django-enumfield-named-choices
用法
创建枚举类并将其作为第一个参数传递给django模型枚举字段。
fromdjango.dbimportmodelsfromdjango_enumfield_named_choicesimportenumclassBeerStyle(enum.Enum):LAGER=0STOUT=1WEISSBIER=2classBeer(models.Model):style=enum.EnumField(BeerStyle,default=BeerStyle.LAGER)
Beer.objects.create(style=BeerStyle.STOUT)Beer.objects.filter(style=BeerStyle.STOUT)
您可以为枚举项使用自己的标签
classAnimals(enum.Enum):CAT=1DOG=2labels={CAT:'Cat',DOG:'Dog'}
枚举类提供了使用转换验证的可能性。
fromdjango.dbimportmodelsfromdjango_enumfield_named_choicesimportenumclassPersonStatus(enum.Enum):ALIVE=1DEAD=2REANIMATED=3_transitions={DEAD:(ALIVE,),REANIMATED:(DEAD,)}classPerson(models.Model):status=enum.EnumField(PersonStatus)
这些转变表明,一个人只能从活着到死,从死到复活。
person=Person.objects.create(status=PersonStatus.ALIVE)try:person.status=PersonStatus.REANIMATEDperson.save()exceptInvalidStatusOperationError:print("Person status can not go from ALIVE to REANIMATED")
枚举类也可以在没有EnumField的情况下使用。这在django form choicefields中非常有用。
fromdjango.formsimportFormfromdjango_enumfield_named_choicesimportenumclassGenderEnum(enum.Enum):MALE=1FEMALE=2labels={MALE:'Male',FEMALE:'Female',}classPersonForm(forms.Form)gender=forms.TypedChoiceField(choices=GenderEnum.choices(),coerce=int)
在模板中呈现personform将生成一个选择框,其中“男性”和“女性”作为性别字段的选项标签。
如果要将此包与django restful framework和django filter一起使用, django url filter,以及djangorestframework filters包,对命名的 枚举类型的值而不是它们的数值对应值可以在 枚举类型接口的值类型为str,默认设置为int类型,如下所示。
# in enums.pyfromdjango_enumfield_named_choicesimportenumclassGenderEnum(enum.Enum):MALE=1FEMALE=2labels={MALE:'Male',FEMALE:'Female',}interface=str# in models.pyfromdjango_enumfield_named_choices.db.fieldsimportEnumFieldclassPerson(models.Model):name=...gender=EnumField(GenderEnum)# and then when you expose you model through API endpoint# you can filter it with following URL request# /person/?gender=male# instead of# /person/?gender=1# thought the actual values of enum in the database are still integers.