-
Hi all! I'm converting our project from Django to Django Ninja. Before we used to return a response object that would look something like this: class AssetResponse:
def __init__(self, text, url, thumbnail):
self.text = text
self.url = url
self.thumbnail = thumbnail
def to_dict(self) -> dict:
return {
"name": self.text,
"url": self.url,
"thumbnail": self.thumbnail,
}
def to_asset(self) -> Asset:
return Asset(name=self.text, url=self.url) The nice thing here is I can use mypy to make sure the class is created correctly. So nobody can do `response = AssetResponse(Text, URL, ThUmBnail) without seeing an error. But now I converted it to a schema: class AssetResponse(Schema):
text: str
url: str
thumbnail: str But when creating this class it shows as: With **data: Any, so I can no longer ensure the types. Is there any way around this? Or am I structuring this wrong in the first place? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
@Johnhersh well this is default behaviour of pydantic.BaseModel (and Schema inherited from it) as it can validate all sort of input data and turn it into a valid types Personally I do not see why you would need to create Schema objects directly as validation of the response object will happen automatically: class AssetResponse(Schema):
text: str
url: str
thumbnail: str
@api.get('/asset', response=AssetResponse)
def get_asset(request):
return {
"text": "foo",
"url": "https://gihub.com",
"thumbnail": "/some.jpg",
} |
Beta Was this translation helpful? Give feedback.
yeah, indeed at this moment there are no nice solution
but I'm planning somewhere in the future add suppport for pydantic dataclasses that should basically cover your case