[英]How can I combine/nest EnumFields in Django?
Django-EnumFields lets you combine Enum fields in Django (the clue was in the title). Django-EnumFields可让您在Django中合并Enum字段(线索在标题中)。
Can you combine nest these? 你能把这些嵌套吗?
Here's an example that plays off the docs : 这是一个处理文档的示例:
from django.db import models
from django_enumfield import enum
class BeerStyle(enum.Enum):
LAGER = 0
STOUT = 1
WEISSBIER = 2
class SoftDrinkStyle(enum.Enum):
COKE = 3
LEMONADE = 4
class Drink(models.Model):
style = enum.EnumField(????, default=BeerStyle.LAGER)
I don't know what would go in place of ????
我不知道会代替什么????
, or if there is a better way to get this nested/combination to play out with Django. ,或者是否有更好的方法来使此嵌套/组合与Django一起使用。 I'm mainly asking as I want Enum behaviour, with the ability to probe different types, eg in a save method, check for User
age if the Drink is or type Beer
. 我主要是想查询枚举行为,因为它具有探测不同类型的能力,例如在保存方法中,检查是否为User
年龄(如果Drink是)或键入Beer
。
Is this possible? 这可能吗? Having played with this for a bit I don't see how. 玩了一段时间我不知道如何。
Having looked over how Python Enums work, this looks like the best behaviour to mock up 'subclasses' 研究了Python枚举的工作原理后,这似乎是模拟“子类”的最佳行为
from django.db import models
from django_enumfield import enum
class DrinkStyle(enum.Enum):
LAGER = (0, 'Beer')
STOUT = (1, 'Beer')
WEISSBIER = (2, 'Beer')
COKE = (3, 'SoftDrink')
LEMONADE = (4, 'SoftDrink')
def __init__(self, id, drink_type):
self.id = id
self.type = drink_type
@property
def type(self):
return self.drink_type
class Drink(models.Model):
style = enum.EnumField(DrinkStyle, default=DrinkStyle.LAGER)
Then use DrinkStyle.COKE.type
to return the type. 然后使用DrinkStyle.COKE.type
返回类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.