2
2
from promise import is_thenable , Promise
3
3
from sqlalchemy .orm .query import Query
4
4
5
- from graphene .relay import ConnectionField
5
+ from graphene .relay import Connection , ConnectionField
6
6
from graphene .relay .connection import PageInfo
7
7
from graphql_relay .connection .arrayconnection import connection_from_list_slice
8
8
9
- from .utils import get_query
9
+ from .utils import get_query , sort_argument_for_model
10
10
11
11
12
- class SQLAlchemyConnectionField (ConnectionField ):
12
+ class UnsortedSQLAlchemyConnectionField (ConnectionField ):
13
13
14
14
@property
15
15
def model (self ):
16
16
return self .type ._meta .node ._meta .model
17
17
18
18
@classmethod
19
- def get_query (cls , model , info , ** args ):
20
- return get_query (model , info .context )
19
+ def get_query (cls , model , info , sort = None , ** args ):
20
+ query = get_query (model , info .context )
21
+ if sort is not None :
22
+ if isinstance (sort , str ):
23
+ query = query .order_by (sort .value )
24
+ else :
25
+ query = query .order_by (* (col .value for col in sort ))
26
+ return query
21
27
22
28
@classmethod
23
29
def resolve_connection (cls , connection_type , model , info , args , resolved ):
@@ -55,7 +61,25 @@ def get_resolver(self, parent_resolver):
55
61
return partial (self .connection_resolver , parent_resolver , self .type , self .model )
56
62
57
63
58
- __connectionFactory = SQLAlchemyConnectionField
64
+ class SQLAlchemyConnectionField (UnsortedSQLAlchemyConnectionField ):
65
+
66
+ def __init__ (self , type , * args , ** kwargs ):
67
+ if 'sort' not in kwargs and issubclass (type , Connection ):
68
+ # Let super class raise if type is not a Connection
69
+ try :
70
+ model = type .Edge .node ._type ._meta .model
71
+ kwargs .setdefault ('sort' , sort_argument_for_model (model ))
72
+ except Exception :
73
+ raise Exception (
74
+ 'Cannot create sort argument for {}. A model is required. Set the "sort" argument'
75
+ ' to None to disabling the creation of the sort query argument' .format (type .__name__ )
76
+ )
77
+ elif 'sort' in kwargs and kwargs ['sort' ] is None :
78
+ del kwargs ['sort' ]
79
+ super (SQLAlchemyConnectionField , self ).__init__ (type , * args , ** kwargs )
80
+
81
+
82
+ __connectionFactory = UnsortedSQLAlchemyConnectionField
59
83
60
84
61
85
def createConnectionField (_type ):
@@ -69,4 +93,4 @@ def registerConnectionFieldFactory(factoryMethod):
69
93
70
94
def unregisterConnectionFieldFactory ():
71
95
global __connectionFactory
72
- __connectionFactory = SQLAlchemyConnectionField
96
+ __connectionFactory = UnsortedSQLAlchemyConnectionField
0 commit comments