我正在构建一个简单的配方存储应用程序,该应用程序将Graphene软件包用于GraphQL。到目前为止,我已经很容易在变体中使用Django Forms,但是我的模型字段之一实际上是一个Enum,我想将其公开在Graphene / GraphQL中。
我的枚举:
class Unit(Enum):
# Volume
TEASPOON = "teaspoon"
TABLESPOON = "tablespoon"
FLUID_OUNCE = "fl oz"
CUP = "cup"
US_PINT = "us pint"
IMPERIAL_PINT = "imperial pint"
US_QUART = "us quart"
IMPERIAL_QUART = "imperial quart"
US_GALLON = "us gallon"
IMPERIAL_GALLON = "imperial gallon"
MILLILITER = "milliliter"
LITER = "liter"
# Mass and Weight
POUND = "pound"
OUNCE = "ounce"
MILLIGRAM = "milligram"
GRAM = "gram"
KILOGRAM = "kilogram"
我的模特:
class RecipeIngredient(TimeStampedModel):
recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, related_name='ingredients')
direction = models.ForeignKey(RecipeDirection, on_delete=models.CASCADE, null=True, related_name='ingredients')
quantity = models.DecimalField(decimal_places=2, max_digits=10)
unit = models.TextField(choices=Unit.as_tuple_list())
我的表单:
class RecipeIngredientForm(forms.ModelForm):
class Meta:
model = RecipeIngredient
fields = (
'recipe',
'direction',
'quantity',
'unit',
)
我的变异:
class CreateRecipeIngredientMutation(DjangoModelFormMutation):
class Meta:
form_class = RecipeIngredientForm
exclude_fields = ('id',)
我已经创建了这个石墨烯枚举UnitEnum = Enum.from_enum(Unit)
,但是我还无法获得石墨烯来对其进行提取。我尝试将其作为CreateRecipeIngredientMutation
之类的常规字段以及该突变的Input类添加到unit = UnitEnum()
中。到目前为止,我最接近的是前一段时间的Github issue。在iPython shell中玩完该类之后,我认为我可以做CreateRecipeIngredientMutation.Input.unit.type.of_type = UnitEnum()
,但这感觉很糟糕。
答案 0 :(得分:0)
我想出了一个可行但不漂亮的解决方案。我使用了https://github.com/hzdg/django-enumfields软件包来解决这个问题。
我创建了自己的表单字段:
class EnumChoiceField(enumfields.forms.EnumChoiceField):
def __init__(self, enum, *, coerce=lambda val: val, empty_value='', **kwargs):
if isinstance(enum, six.string_types):
self.enum = import_string(enum)
else:
self.enum = enum
super().__init__(coerce=coerce, empty_value=empty_value, **kwargs)
并以我的Django形式使用它。然后在我的自定义AppConfig中,我做到了:
class CoreAppConfig(AppConfig):
name = 'myapp.core'
def ready(self):
registry = get_global_registry()
@convert_form_field.register(EnumChoiceField)
def convert_form_field_to_enum(field: EnumChoiceField):
converted = registry.get_converted_field(field.enum)
if converted is None:
raise ImproperlyConfigured("Enum %r is not registered." % field.enum)
return converted(description=field.help_text, required=field.required)
最后是我的模式:
UnitEnum = Enum.from_enum(Unit)
get_global_registry().register_converted_field(Unit, UnitEnum)
我真的不喜欢这个,但是想不出更好的方法来解决这个问题。我在https://github.com/graphql-python/graphene-django/issues/481#issuecomment-412227036上搜索另一个石墨烯django问题时遇到了这个想法。
我觉得在那里有是一种更好的方法。