Open akkim2 opened 3 months ago
In case anyone is interested, I was able to find a workaround:
+ from typing import Optional, ForwardRef
+ SelfReferenceSchema = ForwardRef('SelfReferenceSchema')
class SelfReferenceSchema(ModelSchema):
- parent: 'SelfReferenceSchema' = None
+ parent: Optional[SelfReferenceSchema]
class Meta:
model = SelfReferenceModel
fields = ['id', 'text']
- SelfReferenceSchema.update_forward_refs()
class SelfReferenceTestOut(ModelSchema):
self_reference: SelfReferenceSchema
class Meta:
model = SelfReferenceMainModel
fields = ["id"]
@router.post("/self-reference-test", response={200: SelfReferenceTestOut})
def self_reference_test(request):
question_stack = SelfReferenceModel.objects.get(pk=1)
return 200, question_stack
Self-referencing schemas seem to be broken when following the Django Ninja documentation, producing incorrect and unusable OpenAPI schema and endpoints.
For example, using the following models:
Loaded with the following data:
[{"model": "questions.selfreferencemainmodel", "pk": 1, "fields": {"self_reference": 1}}, {"model": "questions.selfreferencemodel", "pk": 1, "fields": {"parent": null, "text": "Test 1"}}, {"model": "questions.selfreferencemodel", "pk": 2, "fields": {"parent": 1, "text": "Test 2"}}]
And the following API:
Results in errors in the OpenAPI docs:
And shows an incorrect schema (where
parent
is shown as astring
):When the endpoint is executed, the following error is returned:
Lastly, here is the generated OpenAPI.json:
Thank you for your assistance in advance!
Versions (please complete the following information):