Repository navigation
|
I am using Django-Ninja to expose configuration in a format that a legacy application can read. In multiple places names are used as dictionary keys. How can I write a schema that handles that? Reduced example: {
"Environment": {
"enabled": true,
"mapping": {
"Item1": {},
"Item2": {}
}
}
}As a workaround I have removed the response schema and manually built dictionaries to return, but then much of Ninjas validation and functions for excluding fields is lost. result = {}
result[environment.name] = {
"enabled": True,
"mapping": {}
}
for item in items:
result[environment.name]["mapping"][item.name] = {} |
Replies: 1 comment 3 replies
|
You can keep the response schema here. The dynamic part should be typed as a mapping: from typing import Dict
from ninja import Schema
class ItemConfig(Schema):
pass
class EnvironmentConfig(Schema):
enabled: bool
mapping: Dict[str, ItemConfig]
EnvironmentResponse = Dict[str, EnvironmentConfig]
@api.get("/config", response=EnvironmentResponse)
def get_config(request):
return {
"Environment": {
"enabled": True,
"mapping": {
"Item1": {},
"Item2": {},
},
}
}For your real data, replace This works because If the item objects are not actually empty, put their fields in |
You can keep the response schema here. The dynamic part should be typed as a mapping:
For your real data, replace
"Environment"/"Item1"with generated keys.This works because
Schemais still a Pydantic model, and …