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

我正在构建一个简单的配方存储应用程序,该应用程序将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(),但这感觉很糟糕。

参考方案

我想出了一个可行但不漂亮的解决方案。我使用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问题时,我遇到了这个想法。

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

用大写字母拆分字符串,但忽略AAA Python Regex - python

我的正则表达式:vendor = "MyNameIsJoe. I'mWorkerInAAAinc." ven = re.split(r'(?<=[a-z])[A-Z]|[A-Z](?=[a-z])', vendor) 以大写字母分割字符串,例如:'我的名字是乔。 I'mWorkerInAAAinc”变成…

您如何在列表内部调用一个字符串位置? - python

我一直在做迷宫游戏。我首先决定制作一个迷你教程。游戏开发才刚刚开始,现在我正在尝试使其向上发展。我正在尝试更改PlayerAre变量,但是它不起作用。我试过放在列表内和列表外。maze = ["o","*","*","*","*","*",…

Python-crontab模块 - python

我正在尝试在Linux OS(CentOS 7)上使用Python-crontab模块我的配置文件如下:{ "ossConfigurationData": { "work1": [ { "cronInterval": "0 0 0 1 1 ?", "attribute&…

在返回'Response'(Python)中传递多个参数 - python

我在Angular工作,正在使用Http请求和响应。是否可以在“响应”中发送多个参数。角度文件:this.http.get("api/agent/applicationaware").subscribe((data:any)... python文件:def get(request): ... return Response(seriali…

Python exchangelib在子文件夹中读取邮件 - python

我想从Outlook邮箱的子文件夹中读取邮件。Inbox ├──myfolder 我可以使用account.inbox.all()阅读收件箱,但我想阅读myfolder中的邮件我尝试了此页面folder部分中的内容,但无法正确完成https://pypi.python.org/pypi/exchangelib/ 参考方案 您需要首先掌握Folder的myfo…