GraphQL + Django: resolve queries using raw PostgreSQL query
Default resolvers on GraphQL Python / Graphene try to do the resolution of a given field_name in a root object using getattr.
So, for example, the default resolver for a field named order_items
will be something like:
def resolver(root, args, context, info):
return getattr(root, 'order_items', None)
Knowing that, when doing a getattr
in a dict
, the result will be None
(for accessing dict items you will have to use __getitem__
/ dict[key]
).
So, solving your problem could be as easy as change from dicts
to storing the content to namedtuples
.
import graphene
from django.db import connection
from collections import namedtuple
class OrderItemType(graphene.ObjectType):
date = graphene.core.types.custom_scalars.DateTime()
order_id = graphene.ID()
uuid = graphene.String()
class QueryType(graphene.ObjectType):
class Meta:
type_name = 'Query' # This will be name in graphene 1.0
order_items = graphene.List(OrderItemType)
def resolve_order_items(root, args, info):
return get_order_items()
def get_db_rows(sql, args=None):
cursor = connection.cursor()
cursor.execute(sql, args)
columns = [col[0] for col in cursor.description]
RowType = namedtuple('Row', columns)
data = [
RowType(*row) # Edited by John suggestion fix
for row in cursor.fetchall() ]
cursor.close()
return data
def get_order_items():
return get_db_rows("""
SELECT j.created_dt AS date, j.order_id, j.uuid
FROM job AS j
LIMIT 3;
""")
Hope this helps!