7đź‘Ť
The code comments say
GraphQL serializes Enum values as strings, however internally Enums
can be represented by any kind of type, often integers.
So for your particular case, you’re not going to be able to replace the over-the-wire values with integers easily. But it may not matter if the actual value represented by the strings (“A_1”) is still an integer internally and on the client end (from the field’s description values.)
In general though you can replace the automatically generated field for the field with choices by defining an enum class and adding to the definition of the DjangoObjectType
. Here’s an example using the documentation Enum example…
class Episode(graphene.Enum):
NEWHOPE = 4
EMPIRE = 5
JEDI = 6
@property
def description(self):
if self == Episode.NEWHOPE:
return 'New Hope Episode'
return 'Other episode'
which you could then add to your DjangoObjectType
like
class FooType(DjangoObjectType):
score = Episode()
class Meta:
model = Foo
Or if you want to get extra fancy you can generate the Enum field dynamically from your field’s choices in Foo._meta.get_field('score').choices
. See graphene_django.converter.convert_django_field_with_choices
.
5đź‘Ť
You can set convert_choices_to_enum
to False in your Graphene-Django model which will leave them as integers.
class FooType(DjangoObjectType):
class Meta:
model = Foo
convert_choices_to_enum = False
There is more information on the setting here.
- Configuring root logger in python
- How to upload multiple Images using DJango Rest Framework?
- How to pass the remote IP to a proxied service? – Nginx
- Django FloatField in ModelForm with 2 precision point
1đź‘Ť
Having just bumped into this myself, an alternate is to define your field outside of the Meta (use only_fields
) as just a graphene.Int
, then you can provide your own resolver function and just return the value of the field, which will end up as a number.
My code snippet (the problem field was resource_type
which is the Enum):
class ResourceItem(DjangoObjectType):
class Meta:
model = Resource
only_fields = (
"id",
"title",
"description",
"icon",
"target",
"session_reveal",
"metadata",
"payload",
)
resource_type = graphene.Int()
def resolve_resource_type(self, info):
return self.resource_type
- Django View Causes Psycopg2 Cursor Does/Does Not Exist Error
- Django: Signal on queryset.update
- Django admin, custom error message?
- Celery does not registering tasks
- Psycopg2.DataError: invalid input syntax for integer: "test" Getting error when moving code to test server