Improved Django List retreival and added extra tests.

This commit is contained in:
Syrus Akbary 2016-09-21 19:32:39 -07:00
parent 9cfe337032
commit 7fbc3e69b1
5 changed files with 42 additions and 7 deletions

View File

@ -33,6 +33,9 @@ def initialize():
)
xwing.save()
human.ship = xwing
human.save()
ywing = Ship(
id='2',
name='Y-Wing',

View File

@ -5,6 +5,7 @@ from django.db import models
class Character(models.Model):
name = models.CharField(max_length=50)
ship = models.ForeignKey('Ship', blank=True, null=True, related_name='characters')
def __str__(self):
return self.name

View File

@ -45,3 +45,30 @@ def test_correct_fetch_first_ship_rebels():
result = schema.execute(query)
assert not result.errors
assert result.data == expected
def test_correct_list_characters():
initialize()
query = '''
query RebelsShipsQuery {
node(id: "U2hpcDox") {
... on Ship {
name
characters {
name
}
}
}
}
'''
expected = {
'node': {
'name': 'X-Wing',
'characters': [{
'name': 'Human'
}],
}
}
result = schema.execute(query)
assert not result.errors
assert result.data == expected

View File

@ -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, DjangoToManyField
from .fields import get_connection_field, DjangoListField
from .utils import get_related_model, import_single_dispatch
singledispatch = import_single_dispatch()
@ -133,7 +133,7 @@ def convert_field_to_list_or_connection(field, registry=None):
if is_node(_type):
return get_connection_field(_type)
return DjangoToManyField(_type)
return DjangoListField(_type)
return Dynamic(dynamic_type)
@ -153,7 +153,7 @@ def convert_relatedfield_to_djangomodel(field, registry=None):
if is_node(_type):
return get_connection_field(_type)
return DjangoToManyField(_type)
return DjangoListField(_type)
return Dynamic(dynamic_type)

View File

@ -9,17 +9,21 @@ from graphql_relay.connection.arrayconnection import connection_from_list_slice
from .utils import DJANGO_FILTER_INSTALLED, maybe_queryset
class DjangoToManyField(Field):
class DjangoListField(Field):
def __init__(self, _type, *args, **kwargs):
return super(DjangoToManyField, self).__init__(List(_type), *args, **kwargs)
return super(DjangoListField, self).__init__(List(_type), *args, **kwargs)
@property
def model(self):
return self.type.of_type._meta.node._meta.model
@staticmethod
def rel_resolver(resolver, root, args, context, info):
def list_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)
return partial(self.list_resolver, parent_resolver)
class DjangoConnectionField(ConnectionField):