简体   繁体   中英

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.

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,

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). Since these Enums are stored in our database as strings like THE_ENUM_VALUE , this is all graphene returns.

So I suppose I have two questions:

  1. Is this even the correct way to return this kind of payload with 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? (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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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