如何在石墨烯中覆盖DjangoModelFormMutation字段类型?

问题描述 投票:2回答:1

我正在构建一个简单的配方存储应用程序,它使用Graphp的Graphene包。到目前为止,我已经能够很容易地在我的突变中使用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',)

我已经创建了这个石墨烯enum UnitEnum = Enum.from_enum(Unit)但是我还没能得到石墨烯来接它。我已经尝试将它添加到CreateRecipeIngredientMutation作为常规字段,如unit = UnitEnum()以及该突变的输入类。到目前为止,我最接近的是前一段时间的Github issue。在iPython shell中使用该类后,我想我可以做CreateRecipeIngredientMutation.Input.unit.type.of_type = UnitEnum(),但这感觉很糟糕。

python django graphql graphene-python
1个回答
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问题时,我遇到了这个想法。

我觉得必须有一个更好的方法来做到这一点。

© www.soinside.com 2019 - 2024. All rights reserved.