2016-06-20 00:30:33 +03:00
|
|
|
from django.db.models.query import QuerySet
|
2016-06-17 19:29:38 +03:00
|
|
|
from graphene.relay import ConnectionField
|
2016-06-20 00:30:33 +03:00
|
|
|
from graphql_relay.connection.arrayconnection import connection_from_list_slice
|
|
|
|
from .utils import maybe_queryset
|
2016-06-17 19:29:38 +03:00
|
|
|
|
|
|
|
|
|
|
|
class DjangoConnectionField(ConnectionField):
|
|
|
|
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
self.on = kwargs.pop('on', False)
|
|
|
|
return super(DjangoConnectionField, self).__init__(*args, **kwargs)
|
|
|
|
|
|
|
|
@property
|
|
|
|
def model(self):
|
2016-06-20 00:30:33 +03:00
|
|
|
return self.connection._meta.node._meta.model
|
2016-06-17 19:29:38 +03:00
|
|
|
|
|
|
|
def get_manager(self):
|
|
|
|
if self.on:
|
|
|
|
return getattr(self.model, self.on)
|
|
|
|
else:
|
|
|
|
return self.model._default_manager
|
|
|
|
|
2016-06-20 00:30:33 +03:00
|
|
|
def default_resolver(self, root, args, context, info):
|
|
|
|
return getattr(root, self.source or self.attname, self.get_manager())
|
2016-06-17 19:29:38 +03:00
|
|
|
|
2016-06-20 00:30:33 +03:00
|
|
|
def connection_resolver(self, root, args, context, info):
|
|
|
|
iterable = super(ConnectionField, self).resolver(root, args, context, info)
|
|
|
|
iterable = maybe_queryset(iterable)
|
|
|
|
if isinstance(iterable, QuerySet):
|
|
|
|
_len = iterable.count()
|
|
|
|
else:
|
|
|
|
_len = len(iterable)
|
|
|
|
return connection_from_list_slice(
|
|
|
|
iterable,
|
|
|
|
args,
|
|
|
|
slice_start=0,
|
|
|
|
list_length=_len,
|
|
|
|
list_slice_length=_len,
|
|
|
|
connection_type=self.connection,
|
|
|
|
edge_type=self.connection.Edge,
|
|
|
|
)
|