简体   繁体   English

Graphene:自定义 Enum 的序列化方式

[英]Graphene: customizing how Enum is serialized

Our backend uses SQLAlchemy as our ORM, and I've recently been playing around with exposing a graphql API, but am having a hard time figuring out how to customize how Enum is serialized by graphene.我们的后端使用 SQLAlchemy 作为我们的 ORM,我最近一直在玩弄 graphql API,但我很难弄清楚如何自定义石墨烯序列化Enum的方式。

Our SqlAlchemy objects all inherit from a BaseModel we've written, and we've created our own BaseEnum that all db.Enum fields inherit, which we use to customize the fields included in a payload to the client, which is as follows,我们的 SqlAlchemy 对象都继承自我们编写的BaseModel ,我们创建了自己的BaseEnum ,所有db.Enum字段都继承,我们用它来自定义包含在客户端的有效负载中的字段,如下所示,

someEnum: {
    'value': <some_value>,
    'label': <some_label>,
}

I haven't been able to figure out how to get graphene to do the same serialization (or if it is even possible/violates the spirit of grapqhl).我一直无法弄清楚如何让石墨烯进行相同的序列化(或者如果它甚至可能/违反 grapqhl 的精神)。 Since these Enums are stored in our database as strings like THE_ENUM_VALUE , this is all graphene returns.由于这些Enums作为字符串存储在我们的数据库中,如THE_ENUM_VALUE ,这都是石墨烯的回报。

So I suppose I have two questions:所以我想我有两个问题:

  1. Is this even the correct way to return this kind of payload with graphql?这甚至是用 graphql 返回这种有效负载的正确方法吗? Or would it be more proper to have a query like或者像这样的查询会更合适
{
  someModel {
    someEnum {
      label
      value
    }
  }
}
  1. How would I override the serialization of all Enum fields returned by graphene so we don't have to write custom resolvers for every single Enum field?我如何覆盖石墨烯返回的所有Enum字段的序列化,这样我们就不必为每个Enum字段编写自定义解析器? (there are hundreds) (有数百个)

For everyone looking for an answer for the second question对于寻找第二个问题的答案的每个人

       class MyEnum(graphene.Enum,):
            value: <some_value>,
            label: <some_label>,
        
            @property
            def description(self):
                return self.value

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM