Search code examples
pythonenumsgraphene-pythongraphene-sqlalchemy

Add value to existing graphene.Enum


Is there a way to add a value to an existing graphene.Enum?

I want to use graphene-sqlalchemy sort_enum() functionality and to add additional functionality of my own - TOTAL_COUNT_ASC and TOTAL_COUNT_DESC that will enable sorting by total count, but I can figure out how to do it. Directly adding the fields to the graphene.Enum doesn't work:

SqlModel.sort_enum().TOTAL_COUNT_ASC = "TOTAL_COUNT_ASC"

Thanks,


Solution

  • The best way that I found is:

    
    from graphene_sqlalchemy import utils
    
    # Take the original Enum
    ExtendedValues  = [(m.name, m.value) for m in SqlModel.sort_enum()._meta.enum]
    # Add the new values with EnumValue
    ExtendedValues += [("TOTAL_COUNT_ASC", utils.EnumValue('TOTAL_COUNT_ASC', sqlalchemy.func.count())), ('TOTAL_COUNT_DESC', utils.EnumValue('TOTAL_COUNT_DESC', sqlalchemy.func.count().desc()))]
    # Create the extended graphene enum
    ExtendedEnum = graphene.Enum("ExtendedEnum", ExtendedValues)