django-ninja icon indicating copy to clipboard operation
django-ninja copied to clipboard

[BUG] reponse field becomes null if route specified reponse=MySchema

Open samuelchen opened this issue 1 year ago • 2 comments

Describe the bug A clear and concise description of what the bug is.

hello, I have a general ApiResposne schema

class ApiResponse(Schema):
    code: int = ApiRespCode.SUCCESS
    message: Optional[str | Promise] = ""
    data: Any = None

the api definition is:

@msg_router.get("/foo/")
async def message_foo(request: HttpRequest) -> ApiResponse:
    return ApiResults.SUCCESS(data="foo")

if runs well and return expected data.

{
    "code": 0,
    "message": "Succeed",
    "data": "foo"
}

but if I add resposne=ApiResposne to router, it returns with data:null

{
    "code": 0,
    "message": "Succeed",
    "data": null
}

Versions (please complete the following information):

  • Python version: 3.11
  • Django version: 4.2
  • Django-Ninja version: 1.0.1
  • Pydantic version: 2.1.1

samuelchen avatar Dec 04 '23 10:12 samuelchen

@samuelchen could you show definition for

  • ApiRespCode.SUCCESS
  • Promise
  • code for def ApiResults.SUCCESS

vitalik avatar Dec 04 '23 12:12 vitalik

Sure, thank you for your response. @vitalik

Promise is a lazy object.

def _(message: str) -> Promise:
    return pgettext_lazy("api_resp", message)
class ApiRespCode:
    SUCCESS: int = 0
class ApiResults:
    # common result
    SUCCESS: R = R(code=ApiRespCode.SUCCESS, message=_("Succeed"))
class ApiResponse(Schema):
    code: int = ApiRespCode.SUCCESS
    message: Optional[str | Promise] = ""
    data: Any = None  

    class Config:
        arbitrary_types_allowed = True

    def __call__(self, data: Any = None) -> Self:
        self.data = data
        return self

samuelchen avatar Dec 04 '23 12:12 samuelchen