From f747102e35f930472c495168954f7d08b8513a11 Mon Sep 17 00:00:00 2001 From: Patrick Arminio Date: Mon, 26 Jun 2017 12:14:04 +0100 Subject: [PATCH] Add support for rest framework List Field --- .../rest_framework/serializer_converter.py | 24 +++++++++++++++---- .../tests/test_field_converter.py | 17 +++++++++++++ 2 files changed, 36 insertions(+), 5 deletions(-) diff --git a/graphene_django/rest_framework/serializer_converter.py b/graphene_django/rest_framework/serializer_converter.py index dd93135..03ef410 100644 --- a/graphene_django/rest_framework/serializer_converter.py +++ b/graphene_django/rest_framework/serializer_converter.py @@ -38,13 +38,20 @@ def convert_serializer_field(field, is_input=True): and the field itself is required """ - # TODO: sub types? kwargs - graphql_type = get_graphene_type_from_serializer_field(field) - return graphql_type( - description=field.help_text, required=is_input and field.required - ) + kwargs = { + 'description': field.help_text, + 'required': is_input and field.required, + } + + # if it is a tuple or a list it means that we are returning + # the graphql type and the child type + if isinstance(graphql_type, (list, tuple)): + kwargs['of_type'] = graphql_type[1] + graphql_type = graphql_type[0] + + return graphql_type(**kwargs) @get_graphene_type_from_serializer_field.register(serializers.Field) @@ -66,3 +73,10 @@ def convert_serializer_field_to_bool(field): @get_graphene_type_from_serializer_field.register(serializers.DecimalField) def convert_serializer_field_to_float(field): return graphene.Float + + +@get_graphene_type_from_serializer_field.register(serializers.ListField) +def convert_serializer_field_to_list(field, is_input=True): + child_type = get_graphene_type_from_serializer_field(field.child) + + return (graphene.List, child_type) diff --git a/graphene_django/rest_framework/tests/test_field_converter.py b/graphene_django/rest_framework/tests/test_field_converter.py index b3fe495..10b097f 100644 --- a/graphene_django/rest_framework/tests/test_field_converter.py +++ b/graphene_django/rest_framework/tests/test_field_converter.py @@ -98,3 +98,20 @@ def test_should_float_convert_float(): def test_should_decimal_convert_float(): assert_conversion(serializers.DecimalField, graphene.Float, max_digits=4, decimal_places=2) + + +def test_should_list_convert_to_list(): + class StringListField(serializers.ListField): + child = serializers.CharField() + + field_a = assert_conversion( + serializers.ListField, + graphene.List, + child=serializers.IntegerField(min_value=0, max_value=100) + ) + + assert field_a.of_type == graphene.Int + + field_b = assert_conversion(StringListField, graphene.List) + + assert field_b.of_type == graphene.String