From a48abd1d3354b382c2d3042492259fd417ed5d04 Mon Sep 17 00:00:00 2001 From: Alisson Patricio Date: Tue, 6 Feb 2024 23:52:44 -0300 Subject: [PATCH 1/2] Allows field's choices to be a callable Starting in Django 5 field's choices can also be a callable --- graphene_django/converter.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/graphene_django/converter.py b/graphene_django/converter.py index 121c1de1..b73135e3 100644 --- a/graphene_django/converter.py +++ b/graphene_django/converter.py @@ -1,5 +1,6 @@ import inspect from collections import OrderedDict +from collections.abc import Callable from functools import partial, singledispatch, wraps from django.db import models @@ -72,6 +73,8 @@ def convert_choice_name(name): def get_choices(choices): converted_names = [] + if isinstance(choices, Callable): + choices = choices() if isinstance(choices, OrderedDict): choices = choices.items() for value, help_text in choices: From f18ab43ddc3b8ee2402e3731fc7b013fbf19b5e6 Mon Sep 17 00:00:00 2001 From: Alisson Patricio Date: Wed, 7 Feb 2024 15:18:34 -0300 Subject: [PATCH 2/2] test if field with callable choices converts into enum --- graphene_django/tests/test_converter.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/graphene_django/tests/test_converter.py b/graphene_django/tests/test_converter.py index e8c09208..2f8b1d51 100644 --- a/graphene_django/tests/test_converter.py +++ b/graphene_django/tests/test_converter.py @@ -180,6 +180,26 @@ class Meta: assert graphene_type._meta.enum.__members__["EN"].description == "English" +def test_field_with_callable_choices_convert_enum(): + def get_choices(): + return ("es", "Spanish"), ("en", "English") + + field = models.CharField(help_text="Language", choices=get_choices) + + class TranslatedModel(models.Model): + language = field + + class Meta: + app_label = "test" + + graphene_type = convert_django_field_with_choices(field).type.of_type + assert graphene_type._meta.name == "TestTranslatedModelLanguageChoices" + assert graphene_type._meta.enum.__members__["ES"].value == "es" + assert graphene_type._meta.enum.__members__["ES"].description == "Spanish" + assert graphene_type._meta.enum.__members__["EN"].value == "en" + assert graphene_type._meta.enum.__members__["EN"].description == "English" + + def test_field_with_grouped_choices(): field = models.CharField( help_text="Language",