Skip to content

Commit 45c2aa0

Browse files
nossilakiendang
andauthored
Allows field's choices to be a callable (#1497)
* Allows field's choices to be a callable Starting in Django 5 field's choices can also be a callable * test if field with callable choices converts into enum --------- Co-authored-by: Kien Dang <[email protected]>
1 parent ac09cd2 commit 45c2aa0

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

graphene_django/converter.py

+3
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import inspect
2+
from collections.abc import Callable
23
from functools import partial, singledispatch, wraps
34

45
from django.db import models
@@ -71,6 +72,8 @@ def convert_choice_name(name):
7172

7273
def get_choices(choices):
7374
converted_names = []
75+
if isinstance(choices, Callable):
76+
choices = choices()
7477

7578
# In restframework==3.15.0, choices are not passed
7679
# as OrderedDict anymore, so it's safer to check

graphene_django/tests/test_converter.py

+20
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,26 @@ class Meta:
180180
assert graphene_type._meta.enum.__members__["EN"].description == "English"
181181

182182

183+
def test_field_with_callable_choices_convert_enum():
184+
def get_choices():
185+
return ("es", "Spanish"), ("en", "English")
186+
187+
field = models.CharField(help_text="Language", choices=get_choices)
188+
189+
class TranslatedModel(models.Model):
190+
language = field
191+
192+
class Meta:
193+
app_label = "test"
194+
195+
graphene_type = convert_django_field_with_choices(field).type.of_type
196+
assert graphene_type._meta.name == "TestTranslatedModelLanguageChoices"
197+
assert graphene_type._meta.enum.__members__["ES"].value == "es"
198+
assert graphene_type._meta.enum.__members__["ES"].description == "Spanish"
199+
assert graphene_type._meta.enum.__members__["EN"].value == "en"
200+
assert graphene_type._meta.enum.__members__["EN"].description == "English"
201+
202+
183203
def test_field_with_grouped_choices():
184204
field = models.CharField(
185205
help_text="Language",

0 commit comments

Comments
 (0)