From 17178cfcbf922179e783f95ee8f0dd4599d4e074 Mon Sep 17 00:00:00 2001 From: Conrad Kramer Date: Tue, 20 Sep 2016 21:25:05 -0700 Subject: [PATCH] Added a DjangoToManyField to handle to-many relationships To-many relationships return a manager, which needs to be turned into an iterable (its queryset) using `maybe_queryset`. --- graphene_django/converter.py | 7 ++++--- graphene_django/fields.py | 14 ++++++++++++++ 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/graphene_django/converter.py b/graphene_django/converter.py index 4d1e30d..ba898f7 100644 --- a/graphene_django/converter.py +++ b/graphene_django/converter.py @@ -10,7 +10,7 @@ from graphene.utils.str_converters import to_const from .compat import (ArrayField, HStoreField, JSONField, RangeField, RelatedObject, UUIDField) -from .fields import get_connection_field +from .fields import get_connection_field, DjangoToManyField from .utils import get_related_model, import_single_dispatch singledispatch = import_single_dispatch() @@ -132,7 +132,8 @@ def convert_field_to_list_or_connection(field, registry=None): if is_node(_type): return get_connection_field(_type) - return Field(List(_type)) + + return DjangoToManyField(_type) return Dynamic(dynamic_type) @@ -152,7 +153,7 @@ def convert_relatedfield_to_djangomodel(field, registry=None): if is_node(_type): return get_connection_field(_type) - return Field(List(_type)) + return DjangoToManyField(_type) return Dynamic(dynamic_type) diff --git a/graphene_django/fields.py b/graphene_django/fields.py index b882fc3..4d87ae4 100644 --- a/graphene_django/fields.py +++ b/graphene_django/fields.py @@ -2,12 +2,26 @@ from functools import partial from django.db.models.query import QuerySet +from graphene.types import Field, List from graphene.relay import ConnectionField, PageInfo from graphql_relay.connection.arrayconnection import connection_from_list_slice from .utils import DJANGO_FILTER_INSTALLED, maybe_queryset +class DjangoToManyField(Field): + + def __init__(self, _type, *args, **kwargs): + return super(DjangoToManyField, self).__init__(List(_type), *args, **kwargs) + + @staticmethod + def rel_resolver(resolver, root, args, context, info): + return maybe_queryset(resolver(root, args, context, info)) + + def get_resolver(self, parent_resolver): + return partial(self.rel_resolver, parent_resolver) + + class DjangoConnectionField(ConnectionField): def __init__(self, *args, **kwargs):