Drf-yasg: Put model into $ref with @swagger_auto_schema

Created on 14 Sep 2018  路  5Comments  路  Source: axnsan12/drf-yasg

I'm trying to manually define a model multiple times but my generator create one model per request instead of reusing the same object, so I want to put it into ref definition to be reused.
I can't manage to do it, here is what I've tried:

definitions = openapi.ReferenceResolver(openapi.SCHEMA_DEFINITIONS)
definitions.set('ReceiptRequest', openapi.Schema(type=openapi.TYPE_OBJECT,
                                                 properties={
                                                     'method': openapi.Schema(type=openapi.TYPE_STRING)},
                                                 required=['method']
                                                 )
                )

RECEIPT_REQUEST_SCHEMA = openapi.SchemaRef(definitions, "ReceiptRequest")

This is not working and give me:

 assert real_scope and real_scope in self._objects, "invalid scope %s" % scope
AssertionError: invalid scope None

If I don't do definitions.set then I get

assert name in self._objects[scope], "#/%s/%s is not defined" % (scope, name)
AssertionError: #/definitions/ReceiptRequest is not defined

How can I achieve this please ?

question

Most helpful comment

Super unclear what the solution is here...

__init__ of what?? -- an example of how to add references would go a long way to resolve confusion.

All 5 comments

This is not working because every run of the schema generator creates a new ReferenceResolver:

https://github.com/axnsan12/drf-yasg/blob/20786e53c3949d14c00d70d112f4452ec850ba5f/src/drf_yasg/generators.py#L211-L215

The way to get access to it would be in a custom SwaggerAutoSchema.

Thanks @axnsan12 any example on how I can do that ? I already have a custom SwaggerAutoSchema but I don't know how can I add myself a model and reference it later where I need into a @swagger_auto_schema...

_(six thousand years later)_

The __init__ method would be a suitable place for this:

definitions = self.components.with_scope(openapi.SCHEMA_DEFINITIONS)
definitions.set('ReceiptRequest', openapi.Schema(type=openapi.TYPE_OBJECT,
                                                 properties={
                                                     'method': openapi.Schema(type=openapi.TYPE_STRING)},
                                                 required=['method']
                                                 )
                )

Super unclear what the solution is here...

__init__ of what?? -- an example of how to add references would go a long way to resolve confusion.

@axnsan12 any example about this??

Was this page helpful?
0 / 5 - 0 ratings

Related issues

maikotz picture maikotz  路  4Comments

therefromhere picture therefromhere  路  3Comments

tiltec picture tiltec  路  4Comments

iamhssingh picture iamhssingh  路  3Comments

csdenboer picture csdenboer  路  3Comments