@@ -161,6 +161,19 @@ def convert_field_to_union(field, registry=None):
161
161
)
162
162
Meta = type ("Meta" , (object ,), {"types" : tuple (_types )})
163
163
_union = type (name , (graphene .Union ,), {"Meta" : Meta })
164
+
165
+ def reference_resolver (root , * args , ** kwargs ):
166
+ dereferenced = getattr (root , field .name or field .db_name )
167
+ document = get_document (dereferenced ["_cls" ])
168
+ document_field = mongoengine .ReferenceField (document )
169
+ document_field = convert_mongoengine_field (document_field , registry )
170
+ document_field_type = document_field .get_type ().type ._meta .name
171
+ only_fields = [to_snake_case (i ) for i in get_query_fields (args [0 ])[document_field_type ].keys ()]
172
+ return document .objects ().no_dereference ().only (* only_fields ).get (pk = dereferenced ["_ref" ].id )
173
+
174
+ if isinstance (field , mongoengine .GenericReferenceField ):
175
+ return graphene .Field (_union , resolver = reference_resolver )
176
+
164
177
return graphene .Field (_union )
165
178
166
179
@@ -172,8 +185,10 @@ def convert_field_to_dynamic(field, registry=None):
172
185
173
186
def reference_resolver (root , * args , ** kwargs ):
174
187
document = getattr (root , field .name or field .db_name )
175
- only_fields = [to_snake_case (i ) for i in get_query_fields (args [0 ]).keys ()]
176
- return field .document_type .objects ().no_dereference ().only (* only_fields ).get (pk = document .id )
188
+ if document :
189
+ only_fields = [to_snake_case (i ) for i in get_query_fields (args [0 ]).keys ()]
190
+ return field .document_type .objects ().no_dereference ().only (* only_fields ).get (pk = document .id )
191
+ return None
177
192
178
193
def cached_reference_resolver (root , * args , ** kwargs ):
179
194
only_fields = [to_snake_case (i ) for i in get_query_fields (args [0 ]).keys ()]
@@ -186,7 +201,7 @@ def dynamic_type():
186
201
return None
187
202
elif isinstance (field , mongoengine .ReferenceField ):
188
203
return graphene .Field (_type , resolver = reference_resolver ,
189
- description = get_field_description (field , registry ))
204
+ description = get_field_description (field , registry ))
190
205
elif isinstance (field , mongoengine .CachedReferenceField ):
191
206
return graphene .Field (_type , resolver = cached_reference_resolver ,
192
207
description = get_field_description (field , registry ))
0 commit comments