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`.
This commit is contained in:
Conrad Kramer 2016-09-20 21:25:05 -07:00
parent 6db3f19896
commit 17178cfcbf
2 changed files with 18 additions and 3 deletions

View File

@ -10,7 +10,7 @@ from graphene.utils.str_converters import to_const
from .compat import (ArrayField, HStoreField, JSONField, RangeField, from .compat import (ArrayField, HStoreField, JSONField, RangeField,
RelatedObject, UUIDField) RelatedObject, UUIDField)
from .fields import get_connection_field from .fields import get_connection_field, DjangoToManyField
from .utils import get_related_model, import_single_dispatch from .utils import get_related_model, import_single_dispatch
singledispatch = 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): if is_node(_type):
return get_connection_field(_type) return get_connection_field(_type)
return Field(List(_type))
return DjangoToManyField(_type)
return Dynamic(dynamic_type) return Dynamic(dynamic_type)
@ -152,7 +153,7 @@ def convert_relatedfield_to_djangomodel(field, registry=None):
if is_node(_type): if is_node(_type):
return get_connection_field(_type) return get_connection_field(_type)
return Field(List(_type)) return DjangoToManyField(_type)
return Dynamic(dynamic_type) return Dynamic(dynamic_type)

View File

@ -2,12 +2,26 @@ from functools import partial
from django.db.models.query import QuerySet from django.db.models.query import QuerySet
from graphene.types import Field, List
from graphene.relay import ConnectionField, PageInfo from graphene.relay import ConnectionField, PageInfo
from graphql_relay.connection.arrayconnection import connection_from_list_slice from graphql_relay.connection.arrayconnection import connection_from_list_slice
from .utils import DJANGO_FILTER_INSTALLED, maybe_queryset 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): class DjangoConnectionField(ConnectionField):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):