Skip to content

Commit

Permalink
Support RecursiveField with 'many' option (#321)
Browse files Browse the repository at this point in the history
  • Loading branch information
rsichnyi authored and axnsan12 committed Feb 25, 2019
1 parent 76c8fe0 commit e538e07
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 4 deletions.
15 changes: 12 additions & 3 deletions src/drf_yasg/inspectors/field.py
Original file line number Diff line number Diff line change
Expand Up @@ -794,10 +794,19 @@ def field_to_swagger_object(self, field, swagger_object_type, use_references, **
if isinstance(field, RecursiveField) and swagger_object_type == openapi.Schema:
assert use_references is True, "Can not create schema for RecursiveField when use_references is False"

ref_name = get_serializer_ref_name(field.proxied)
assert ref_name is not None, "Can't create RecursiveField schema for inline " + str(type(field.proxied))
proxied = field.proxied
if isinstance(field.proxied, serializers.ListSerializer):
proxied = proxied.child

ref_name = get_serializer_ref_name(proxied)
assert ref_name is not None, "Can't create RecursiveField schema for inline " + str(type(proxied))

definitions = self.components.with_scope(openapi.SCHEMA_DEFINITIONS)
return openapi.SchemaRef(definitions, ref_name, ignore_unresolved=True)

ref = openapi.SchemaRef(definitions, ref_name, ignore_unresolved=True)
if isinstance(field.proxied, serializers.ListSerializer):
ref = openapi.Items(type=openapi.TYPE_ARRAY, items=ref)

return ref

return NotHandled
3 changes: 2 additions & 1 deletion testproj/todo/serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,11 @@ class Meta:

class TodoTreeSerializer(serializers.ModelSerializer):
children = serializers.ListField(child=RecursiveField(), source='children.all')
many_children = RecursiveField(many=True, source='children')

class Meta:
model = TodoTree
fields = ('id', 'title', 'children')
fields = ('id', 'title', 'children', 'many_children')


class TodoRecursiveSerializer(serializers.ModelSerializer):
Expand Down
5 changes: 5 additions & 0 deletions tests/reference.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -1617,6 +1617,7 @@ definitions:
required:
- title
- children
- many_children
type: object
properties:
id:
Expand All @@ -1632,6 +1633,10 @@ definitions:
type: array
items:
$ref: '#/definitions/TodoTree'
many_children:
type: array
items:
$ref: '#/definitions/TodoTree'
TodoYetAnother:
required:
- title
Expand Down

0 comments on commit e538e07

Please sign in to comment.